将 arg 传递给 docker build

Pass arg to docker build

我想在 构建时间 期间传递一个变量,并在 运行 上使用该参数启动脚本。我该怎么做?

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

运行:

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

生产:

$var

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.

换句话说,正确的 Dockerfile 应该是:

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

为了正确构建它,您应该 运行:

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

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