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
deathangel908
  • 8,601
  • 8
  • 47
  • 81

1 Answers1

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

Stefano
  • 4,730
  • 1
  • 20
  • 28