3

I want to pass a variable during build time and start the script with this argument on run. How do I do it?

Dockerfile

FROM alpine
ARG var
# ENV var=${var} # doesn't work
CMD ["echo", "${var}"]
# ENTRYPOINT ["echo", "$var"] # doesn't work
# ENTRYPOINT "echo" "$var" # doesn't work

Running:

docker run -t $(docker build  --build-arg  var=hello -q .) 

Produces:

$var
2
  • 1
    try using CMD echo $var Commented Aug 26, 2019 at 16:21
  • 1
    curious because it works fine on my machine... There are 2 differences between our Dockerfiles: ENV var=$var and CMD echo $var Commented Aug 26, 2019 at 16:24

1 Answer 1

4

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.

In other words a correct Dockerfile would be:

FROM alpine
ARG var
ENV var $var
CMD echo $var

In order to build it correctly, you should run:

docker run -t $( docker build --build-arg=var=hello -q . ) 

src: https://docs.docker.com/engine/reference/builder/#cmd

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.