在Docker中构建期间如何设置环境变量 [英] How do I set environment variables during the build in docker

查看:1068
本文介绍了在Docker中构建期间如何设置环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在构建期间将Docker容器中的环境变量设置为未成功。在使用运行命令时设置它们,但是我需要在构建期间设置它们。

I'm trying to set environment variables in docker container during the build but without success. Setting them when using run command works but I need to set them during the build.

Dockerfile

Dockerfile

FROM ubuntu:latest
ARG TEST_ENV=something

命令I 'm用于构建

docker build -t --build-arg TEST_ENV="test" myimage .

运行

docker run -dit myimage

我正在使用

docker exec containerid printenv

,结果是

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=e49c1abfd58b
TERM=xterm
no_proxy=*.local, 169.254/16
HOME=/root

TEST_ENV不存在

TEST_ENV is not present

推荐答案

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=/ 

这篇关于在Docker中构建期间如何设置环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆