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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With