4

上次我检查时,当我这样做时:

FROM x:latest
ENV foo 'bar'

FROM y:latest
RUN echo "$foo"

那么“echo $foo”是空的——有没有办法在多阶段构建中保持 ENV 变量?

4

1 回答 1

4

在这种情况下,构建参数可能对您有用。用户将无法覆盖它,并且它在容器中不可用,但除此之外我认为它适合。

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
于 2019-06-01T02:53:41.817 回答