且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Docker中构建期间如何设置环境变量

更新时间:2022-02-23 22:03:01

ARG 用于设置在 docker build 过程中使用的环境变量 - 它们不是存在于最终图像中,这就是为什么当您使用 docker run 时,您不会看到它们。

ARG is for setting environment variables which are used during the docker build process - they are not present in the final image, which is why you don't see them when you use docker run.

您使用 ARG ,用于仅在构建映像时相关的设置,并且从映像运行的容器不需要这些设置。您可以使用 ENV 在构建期间和容器中使用evnvironment变量。

You use ARG for settings that are only relevant when the image is being built, and aren't needed by containers which you run from the image. You can use ENV for evnvironment variables to use during the build and in containers.

使用此Dockerfile: p>

With this Dockerfile:

FROM ubuntu                                                                                                            
ARG BUILD_TIME=abc                                                                                                     
ENV RUN_TIME=123                                                                                                       
RUN touch /env.txt                                                                                                     
RUN printenv > /env.txt 

您可以像使用一样覆盖构建参数, docker build -t temp --build-arg BUILD_TIME = def。。然后你得到你的期望:

You can override the build arg as you have done with docker build -t temp --build-arg BUILD_TIME=def .. Then you get what you expect:

> docker run temp cat /env.txt                                                                                         
HOSTNAME=b18b9cafe0e0                                                                                                  
RUN_TIME=123                                                                                                           
HOME=/root                                                                                                             
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin                                                      
BUILD_TIME=def                                                                                                         
PWD=/