27

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?

AlexScalar
  • 1,439
  • 3
  • 9
  • 17

1 Answers1

65

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.

AlexScalar
  • 1,439
  • 3
  • 9
  • 17
  • 4
    Image name should be at the last whatsoever :) before that you can use all the options param – sais May 04 '18 at 20:30
  • 13
    This is because everything after the image name is sent as parameters to the entrypoint script. Which by default is /bin/sh -c – Tim Schruben Oct 12 '18 at 12:25
  • This was exactly what I was looking for! Thank you so much. My variables were not found before, but the problem was that they actually appeared as arguments in my script. – Nebulastic May 12 '19 at 10:15
  • 1
    You just saved me _hours_ of "why the hell isn't this working" – simonlchilds Jul 21 '20 at 20:25
  • 1
    Thanks! After hours of "why the hell isn't this working", I finally found this answer :D – J. Willette Aug 01 '20 at 19:48
  • OMG DOCKER DEVS ... Just when about any other tool is working in standard way you had to show off. – Aubergine Sep 14 '20 at 09:29
  • Yes, docker should warn on this... I believe it's so you can chain arguments but when there is no image name after the fact, there are stragglers. – Kevin Parker Jan 26 '21 at 23:45
  • Pfff another hours of work wasted what could be fixed by simply not accepting INVALID input. – Rick Neeft Feb 27 '22 at 20:57