FROM ubuntu as intermediate # 為第一階段構建設置別名,在第二階段引用
ARG TEST=deault_value # 設置環境變量
ENV ENV_TEST=$TEST # 設置環境變量
RUN echo test > /home/test.txt
RUN cat /home/test.txt # 查看文件是否正常
RUN env
RUN env |grep TEST # 查看環境變量是否已設置FROM ubuntu
COPY --from=intermediate /home/test.txt /home/another_test.txt # 將第一階段生成的文件拷貝到第二階段鏡像中
RUN cat /home/another_test.txt # 查看拷貝的文件是否正常
RUN env
RUN env |grep TEST # 查看環境變量是否已設置
多階段構建
root@ubuntu:/home/vickey/test_build# docker build --build-arg TEST=2 -t ubuntu:test-multi-build --no-cache -f ./dockerfile .
Sending build context to Docker daemon 2.56kB
Step 1/12 : FROM ubuntu as intermediate---> 94e814e2efa8
Step 2/12 : ARG TEST=deault_value---> Running in 7da9180a6311
Removing intermediate container 7da9180a6311---> 7e8420f3ecf2
Step 3/12 : ENV ENV_TEST=$TEST---> Running in 256788d179ce
Removing intermediate container 256788d179ce---> 11cf4e0581d9
Step 4/12 : RUN echo test > /home/test.txt---> Running in c84799ba3831
Removing intermediate container c84799ba3831---> f578ca5fe373
Step 5/12 : RUN cat /home/test.txt---> Running in dbf8272fd10c
test
Removing intermediate container dbf8272fd10c---> 9f8720732878
Step 6/12 : RUN env---> Running in 9050cd9e36c9
HOSTNAME=9050cd9e36c9
HOME=/root
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
TEST=2
PWD=/
ENV_TEST=2
Removing intermediate container 9050cd9e36c9---> f1f4daf42cc0
Step 7/12 : RUN env |grep TEST---> Running in 1cc7968144f5
TEST=2
ENV_TEST=2
Removing intermediate container 1cc7968144f5---> c6d390887082
Step 8/12 : FROM ubuntu---> 94e814e2efa8
Step 9/12 : COPY --from=intermediate /home/test.txt /home/another_test.txt---> 27480a945fab
Step 10/12 : RUN cat /home/another_test.txt---> Running in de1f5a999fe1
test
Removing intermediate container de1f5a999fe1---> 16c630eb6b1b
Step 11/12 : RUN env---> Running in d13becd5ae77
HOSTNAME=d13becd5ae77
HOME=/root
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
PWD=/
Removing intermediate container d13becd5ae77---> ea52a6e9a7b2
Step 12/12 : RUN env |grep TEST---> Running in 7ef585772e9a
The command '/bin/sh -c env |grep TEST' returned a non-zero code: 1