Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use environment variables in a docker run command?

Tags:

docker

If I pass an environment variable which is set inside of the container as an argument to docker run, my shell evaluates it. For example:

I want my container to print the value of $FOO which is bar. None of these will work:

# Prints blank line
$ docker run -e FOO=bar ubuntu echo $FOO

# Prints '$FOO'
$ docker run -r FOO=bar ubuntu echo \$FOO
like image 689
damon Avatar asked Sep 05 '15 02:09

damon


People also ask

Can you use environment variables in Dockerfile?

Dockerfile provides a dedicated variable type ENV to create an environment variable. We can access ENV values during the build, as well as once the container runs.

How do I see environment variables in running container?

Fetch Using docker exec Command Here, we are executing the /usr/bin/env utility inside the Docker container. Using this utility, you can view all the environment variables set inside Docker containers.

What is env command in Docker?

The ENV command sets environment variables within the image both when it is built and when it is executed. These variables can be overridden when you launch your image. An environment variable is a name-value pair, which can be accessed by any script or application that runs from the image.

Can Docker access host environment variables?

You can pass the values of environment variables from the host to your containers without much effort. Simply don't specify a value in the command line, and make sure that the environment variable is named the same as the variable the containerized app expects: $ docker run -e var_name (...)


1 Answers

It works if you run echo in a shell:

$ sudo docker run --rm -e FOO=bar ubuntu bash -c 'echo $FOO'
bar

This is because echo is a command (/bin/echo), but it's the shell that does the variable substitution.

like image 50
z0r Avatar answered Sep 28 '22 03:09

z0r