如何在 docker 构建期间设置环境变量 [英] How do I set environment variables during the build in 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
FROM ubuntu:latest
ARG TEST_ENV=something
我用来构建的命令
docker build -t --build-arg TEST_ENV="test" myimage .
跑步
docker run -dit myimage
我正在使用检查可用的环境变量
I'm checking available environment variables by using
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
用于在构建期间和容器中使用的环境变量.
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 environment variables to use during the build and in containers.
有了这个 Dockerfile:
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屋!