可在容器内shell中使用Docker挂载,但不能从Dockerfile中使用

qlvxas9a  于 2022-12-11  发布在  Docker
关注(0)|答案(2)|浏览(109)

我遇到了一个奇怪的情况,从容器中启动的shell可以看到一个已挂载的卷,但由于某种原因,任何CMD都看不到该卷。
我有以下源代码树:

[~/workspace/docker-test]$ tree
.
├── Dockerfile
└── source
    └── file.txt

1 directory, 2 files

Dockerfile所在位置

FROM ubuntu:jammy as prereqs
RUN ls /usr/source

当我构建并运行dockerfile时,不知怎么的它找不到挂载目录

[~/workspace/docker-test]$ docker build -t docker-test . && docker run -it -v $(pwd)/source:/usr/source docker-test
[+] Building 1.6s (5/5) FINISHED
 => [internal] load build definition from Dockerfile                                    0.0s
 => => transferring dockerfile: 36B                                                     0.0s
 => [internal] load .dockerignore                                                       0.0s
 => => transferring context: 2B                                                         0.0s
 => [internal] load metadata for docker.io/library/ubuntu:jammy                         1.1s
 => CACHED [1/2] FROM docker.io/library/ubuntu:jammy@sha256:27cb6e6ccef575a4698b66f5de  0.0s
 => ERROR [2/2] RUN ls /usr/source                                                      0.3s
------
 > [2/2] RUN ls /usr/source:
#5 0.318 ls: cannot access '/usr/source': No such file or directory
------
executor failed running [/bin/sh -c ls /usr/source]: exit code: 2

但是当我从Docker容器中运行shell时,我能够很好地找到它。新的Dockerfile:

FROM ubuntu:jammy as prereqs
# RUN ls /usr/source
CMD ["/bin/bash"]

启动shell,从该shell中可以完全看到已装入的卷。

[~/workspace/docker-test]$ docker build -t docker-test . && docker run -it -v $(pwd)/source:/usr/source docker-test
[+] Building 0.6s (5/5) FINISHED
 => [internal] load build definition from Dockerfile                                    0.0s
 => => transferring dockerfile: 111B                                                    0.0s
 => [internal] load .dockerignore                                                       0.0s
 => => transferring context: 2B                                                         0.0s
 => [internal] load metadata for docker.io/library/ubuntu:jammy                         0.6s
 => CACHED [1/1] FROM docker.io/library/ubuntu:jammy@sha256:27cb6e6ccef575a4698b66f5de  0.0s
 => exporting to image                                                                  0.0s
 => => exporting layers                                                                 0.0s
 => => writing image sha256:aa762c0645f70aea2a82508f0654abb2aadb27d2abf7e971b5eed85a7e  0.0s
 => => naming to docker.io/library/docker-test                                          0.0s

root@d8b3952e2e80:/# ls /usr/source/
file.txt

我不明白为什么它在Dockerfile中不可见,但在容器shell中却完全可见!

7kqas0il

7kqas0il1#

卷仅在运行时装入。正如您在buildrun命令中看到的,卷指定仅在docker run命令中。

9lowa7mx

9lowa7mx2#

RUN ls /usr/sourcedocker build上运行,但CMDdocker run上执行在映像构建时无法装入卷,因此必须在dockerfile内使用COPY命令才能访问映像内外部资源

相关问题