Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing environment variables not working with Docker

Tags:

I am learning how to pass environment variables to Docker containers. While the following works fine,


Dockerfile

FROM ubuntu ENV USERNAME='david' CMD echo "username = $USERNAME" 

Build & run commands

docker build . -t enviro docker run -d enviro 

docker ps -a gives

2a3a69aa7868        enviro              "/bin/sh -c 'echo \"u…" 

docker logs 2a3a69aa7868 gives

username = david 

The following doesn't work


Dockerfile

FROM ubuntu CMD echo "username = $USERNAME" 

Build & run commands

docker build . -t enviro docker run -d enviro -e USERNAME='david' 

Here the run command gives this,

docker: Error response from daemon: OCI runtime create failed:    container_linux.go:348: starting container process caused "exec: \"-e\":    executable file not found in $PATH": unknown. 

While docker ps -a gives

249cb045c26a        enviro              "-e USERNAME=david" 

docker logs 249cb045c26a gives nothing


Any idea, what is going on here? Why is the environment variable not being passed?

like image 383
AlexScalar Avatar asked May 04 '18 18:05

AlexScalar


People also ask

How do I pass an environment variable in Docker run?

If you want to pass a file containing all of your environment variables to a Docker container, you can use the --env-file flag. The --env-file flag allows you to pass a file containing environment variables to a Docker container.

Can Docker container access environment variables?

When we launch our Docker container, we can pass environment variables as key-value pairs directly into the command line using the parameter –env (or its short form -e). As can be seen, the Docker container correctly interprets the variable VARIABLE1.

Does Docker use .env file?

The .env file feature only works when you use the docker-compose up command and does not work with docker stack deploy . Both $VARIABLE and ${VARIABLE} syntax are supported.

Does Docker compose pass environment variables?

Docker Compose allows us to pass environment variables in via command line or to define them in our shell. However, it's best to keep these values inside the actual Compose file and out of the command line.


1 Answers

OK, I got it. Instead of the following,

docker run -d enviro -e USERNAME='david' 

it must be like this

docker run -d -e USERNAME='david' enviro  

No idea, why docker requires the environment variable before the image's name though.

like image 93
AlexScalar Avatar answered Sep 28 '22 09:09

AlexScalar