建立Docker映像的RUN指令

时间:2020-04-27 10:04:49

标签: docker dockerfile docker-build docker-run

下面是我的Docker文件

ARG tag_info=latest
FROM alpine:${tag_info} AS my_apline
ARG message='Hello World'
RUN echo ${message}
RUN echo ${message} > myfile.txt
RUN echo "Hi Harry"

我运行docker image build -t myimage:v1_0 - < Dockerfile

输出为:

Sending build context to Docker daemon  2.048kB
Step 1/6 : ARG tag_info=latest
Step 2/6 : FROM alpine:${tag_info} AS my_apline
latest: Pulling from library/alpine
cbdbe7a5bc2a: Already exists
Digest: sha256:9a839e63dad54c3a6d1834e29692c8492d93f90c59c978c1ed79109ea4fb9a54
Status: Downloaded newer image for alpine:latest
 ---> f70734b6a266
Step 3/6 : ARG message='Hello World'
 ---> Running in 74bcc8897e8e
Removing intermediate container 74bcc8897e8e
 ---> d8d50432d375
Step 4/6 : RUN echo ${message}
 ---> Running in 730ed8e1c1d3
Hello World
Removing intermediate container 730ed8e1c1d3
 ---> 8417e3167e80
Step 5/6 : RUN echo ${message} > myfile.txt
 ---> Running in c66018331383
Removing intermediate container c66018331383
 ---> 07dc27d8ad3d
Step 6/6 : RUN echo "Hi Harry"
 ---> Running in fb92fb234e42
Hi Harry
Removing intermediate container fb92fb234e42
 ---> a3bec122a77f

它在中间显示“嗨哈里”和“世界你好”(我不明白为什么)

为什么当我从图像文件中旋转容器时,为什么不显示“嗨哈利”和“ Hello World”?

2 个答案:

答案 0 :(得分:1)

因为RUN命令在构建映像时执行命令,而不是在使用映像旋转容器时执行命令。它用于更改图像,例如使用apt-get添加新软件包或更改文件权限等

如果在容器启动时需要运行某些内容,则需要使用commandentrypoint的指令

答案 1 :(得分:1)

来自docker官方文档:

The RUN instruction will execute any commands in a new layer on top of the current image and commit the results. The resulting committed image will be used for the next step in the Dockerfile.

如果要获得描述的行为,则应使用CMD

The main purpose of a CMD is to provide defaults for an executing container. These defaults can include an executable, or they can omit the executable, in which case you must specify an ENTRYPOINT instruction as well.

这具有三种形式:

 - CMD ["executable","param1","param2"] (exec form, this is the preferred form)
 - CMD ["param1","param2"] (as default parameters to ENTRYPOINT)
 - CMD command param1 param2 (shell form)