跨多阶段Docker构建坚持ENV变量

时间:2019-05-23 18:31:36

标签: docker docker-multi-stage-build

我上次检查的时间是

FROM x:latest
ENV foo 'bar'

FROM y:latest
RUN echo "$foo"

然后,“ echo $ foo”为空-有没有办法在多阶段构建中保留ENV变量?

1 个答案:

答案 0 :(得分:0)

在这种情况下,build argument可能对您有用。用户将无法覆盖它,并且它在容器中将不可用,但我认为不合适。

FROM alpine
ARG FOO
RUN echo first step FOO is $FOO

FROM alpine
ARG FOO
RUN echo second step FOO is $FOO

要构建,您需要向--build-arg传递值。

$ docker build --build-arg FOO=bar .
Step 1/6 : FROM alpine
 ---> 055936d39205
Step 2/6 : ARG FOO
 ---> Running in 3f5f18206d06
Removing intermediate container 3f5f18206d06
 ---> 2b82e4b958f7
Step 3/6 : RUN echo first step FOO is $FOO
 ---> Running in c0256dfe286d
first step FOO is bar
Removing intermediate container c0256dfe286d
 ---> 79286b74611f
Step 4/6 : FROM alpine
 ---> 055936d39205
Step 5/6 : ARG FOO
 ---> Running in 9fc20546619f
Removing intermediate container 9fc20546619f
 ---> 30325962d73a
Step 6/6 : RUN echo second step FOO is $FOO
 ---> Running in a8906382909a
second step FOO is bar
Removing intermediate container a8906382909a
 ---> 521dbbfa398b
Successfully built 521dbbfa398b