Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Docker ENV in CMD

I am trying to do the following:

  1. Pass a build arg to my docker build command
  2. Store that as an env variable in my container
  3. Use it in my CMD to start when my container launches.

Below is my setup:

FROM ubuntu:xenial

ARG EXECUTABLE

ENV EXECUTABLE ${EXECUTABLE}


CMD ["/opt/foo/bin/${EXECUTABLE}", "-bar"]

Here is how i'm building container

    docker build --build-arg EXECUTABLE=$EXECUTABLE  -t test_image .

Here is how i'm running image

    docker run -d test_image

When I run the container it crashes and tells me

docker: Error response from daemon: OCI runtime create failed: 
container_linux.go:296: starting container process caused 
"exec: \"/opt/foo/bin/${EXECUTABLE}\": stat /opt/foo/bin/${EXECUTABLE}: 
no such file or directory": unknown.
like image 930
LoganHenderson Avatar asked Oct 13 '18 03:10

LoganHenderson


1 Answers

To use environment variables, you need to use shell.
https://docs.docker.com/engine/reference/builder/#cmd

Note: Unlike the shell form, the exec form does not invoke a command shell. This means that normal shell processing does not happen. For example, CMD [ "echo", "$HOME" ] will not do variable substitution on $HOME. If you want shell processing then either use the shell form or execute a shell directly, for example: CMD [ "sh", "-c", "echo $HOME" ]. When using the exec form and executing a shell directly, as in the case for the shell form, it is the shell that is doing the environment variable expansion, not docker.

Based on this, I think you can work fine by the following Dockerfile.

FROM ubuntu:xenial

ARG EXECUTABLE

ENV EXECUTABLE ${EXECUTABLE}

CMD [ "sh", "-c", "/opt/foo/bin/${EXECUTABLE}", "-bar"]
like image 67
kuromoka Avatar answered Oct 01 '22 18:10

kuromoka