dockerfile中的RUN pwd似乎不起作用

新手上路,请多包涵

I am studying on Docker these days and confused that why RUN pwd just does not seem to work while running my docker file.

I am working on IOS

and the full content of my docker file can be seen as below:

FROM ubuntu:latest

MAINTAINER xxx

RUN mkdir -p /ln && echo hello world > /ln/wd6.txt

WORKDIR /ln

RUpwd

CMD ["more" ,"wd6.txt"]

as far as my understanding, after building the docker image with the tag 'wd8'and running it, I supposed the result should show like this

~ % docker run wd8
::::::::::::::
wd6.txt
::::::::::::::
hello world

ln

however, the fact is without ln.

I have tried with RUN $pwd, and also added ENV at the beginning of my dockerfile, both do not work.

Please help point out where the problem is.

上面的内容是因为先在stackoverflow发帖问的,所以直接把问题内容粘贴过来了。。
顺便想问一下所以是不是RUN mkdir 本机存在的一个路径+新文件夹的名字这个命令,其实我理应并不会在本机存在的这个路径下面看到这个被创建的新的文件夹,对吗

阅读 6.7k
3 个回答

你需要理解,“构建时” 和 “运行时” 的区别,Dockerfile 中的命令只是会在构建时,即运行 docker build 命令时运行。

而最终构建完成后使用 docker run 运行镜像时,只会去执行 CMD 或者 Entrypoint 指定的命令。

新手上路,请多包涵

执行pwd命令也是在容器内执行的,在你本地看不到。

Sending build context to Docker daemon  4.096kB
Step 1/6 : FROM centos:8
 ---> 5d0da3dc9764
Step 2/6 : MAINTAINER xxx
 ---> Running in c72a342a017a
Removing intermediate container c72a342a017a
 ---> 7947f7103b66
Step 3/6 : RUN mkdir -p /ln && echo hello world > /ln/wd6.txt
 ---> Running in 055a7d0af981
Removing intermediate container 055a7d0af981
 ---> e69fd87fb072
Step 4/6 : WORKDIR /ln
 ---> Running in 0bcdeb53f677
Removing intermediate container 0bcdeb53f677
 ---> 8d2e09bdc7a5
Step 5/6 : RUN pwd
 ---> Running in 0f78787609b9               // RUN pwd 在这里运行了,并且输出了 /ln 
/ln
Removing intermediate container 0f78787609b9
 ---> 16f63d1be035
Step 6/6 : CMD ["more" ,"wd6.txt"]
 ---> Running in 6dd1a7ef27df
Removing intermediate container 6dd1a7ef27df
 ---> cddc10ddfb94
Successfully built cddc10ddfb94
Successfully tagged test:v1
mn1 test # docker run -it --rm test:v1 
hello world
mn1 test # 

写 Dockerfile 目的是定义一个镜像
docker build 是根据 Dockerfile 的内容构建镜像
定义镜像的目的是为了给 CMD 或者 ENTRYPOINT 提供一个运行环境。

在运行docker run ... 的时候,实际上调用的是 CMD 或者 ENTRYPOINT 或者你手动指定的参数。

如果非要在 docker run 的时候显示pwd的输出,可以把pwd 写在 CMD 里面,而不是 RUN。

RUN只有在build镜像的时候会运行一次,镜像构建完成之后,docker run 的过程中不会去重复构建镜像,所以 RUN pwd不会输出。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题