Dockerfile 中的条件逻辑,使用 --build-arg

Conditional logic in Dockerfile, using --build-arg

假设我有这个:

ARG my_user="root"  # my_user => default is "root"
USER $my_user
ENV USER=$my_user

到目前为止一切都很好,但现在我们到了这里:

ENV HOME="/root"

有没有办法做这样的事情:

ENV HOME $my_user === "root"? "/root" : "/home/$my_user"

显然,这是错误的语法。

我能想到的唯一解决方案是只使用两个 --build-args,像这样:

docker build -t zoom \
    --build-arg my_user="foo"  \
    --build-arg my_home="/home/foo"  \
     .

很遗憾,您不能直接执行此操作

https://forums.docker.com/t/how-do-i-send-runs-output-to-env-in-dockerfile/16106/3

所以你有两个选择

在开始时使用 shell 脚本

您可以在开始时使用 shell 脚本

CMD /start.sh

在你的 start.sh 中你可以有这样的逻辑

if [ $X == "Y" ]; then
   export X=Y
else
   export X=Z
fi

创建配置文件环境变量

FROM alpine

RUN echo "export NAME=TARUN" > /etc/profile.d/myenv.sh
SHELL ["/bin/sh", "-lc"]
CMD env

然后你运行它

$ docker run test
HOSTNAME=d98d44fa1dc9
SHLVL=1
HOME=/root
PAGER=less
PS1=\h:\w$
NAME=TARUN
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
PWD=/
CHARSET=UTF-8

Note: The SHELL ["/bin/sh", "-lc"] is quite important here, else the profile will not be loaded

Note2: Instead of RUN echo "export NAME=TARUN" > /etc/profile.d/myenv.sh you can also do a COPY myevn.sh /etc/profile.d/myenv.sh and have the file be present in your build context