从主机到容器的Dockerfile COPY工作正常,但是当docker-compose.yml使用卷时,容器中的文件对主机不可见

时间:2019-02-12 21:53:37

标签: docker docker-compose dockerfile

使用上下文:

test workspace

目标是将test.txt复制到容器中,并使其在主机的tst文件夹中可见。 tst文件夹包含一个预先存在的文件tst.txt。

使用Docker应用程序:

Docker application

使用.dockerignore:

.DS_Store
.vscode
.dockerignore
Dockerfile
docker-compose.yml
**/tst

使用Dockerfile:

FROM alpine:latest
RUN apk add --no-cache bash
WORKDIR /app
RUN echo "$(echo "pwd:")" "$(pwd)"  <<-- returns pwd: /app 
COPY test.txt .
RUN ls -la . 
CMD ["sh", "-c", "ls -la ."]

使用docker-compose文件:

version: '3.7'
services:
  app:
    build: .
    volumes:
      - ./tst:/app

运行docker-compose up会导致:

Creating network "sof_default" with the default driver
Building app
Step 1/7 : FROM alpine:latest
latest: Pulling from library/alpine
6c40cc604d8e: Downloading [>                                                  
----------
Step 3/7 : WORKDIR /app
---> Running in cf58e5a10d23
Removing intermediate container cf58e5a10d23
---> 76fb51298933
Step 4/7 : RUN echo "$(echo "pwd:")" "$(pwd)"
---> Running in 07135f745883
pwd: /app
Removing intermediate container 07135f745883
---> 45acc1c04a12
Step 5/7 : COPY test.txt .
---> de0ce42397b9
Step 6/7 : RUN ls -la . <<- the output shows test.txt was copied into the container's /app directory
---> Running in 60371e9516c1
total 12
drwxr-xr-x    1 root     root          4096 Feb 12 21:25 .
drwxr-xr-x    1 root     root          4096 Feb 12 21:25 ..
-rw-r--r--    1 root     root            15 Feb 12 19:19 test.txt
Removing intermediate container 60371e9516c1
---> 3d514dac4f61
Step 7/7 : CMD ["sh", "-c", "ls -la . && cat test.txt"]
---> Running in db644643a844
Removing intermediate container db644643a844
---> ad9f6988d31d

Successfully built ad9f6988d31d
Successfully tagged sof_app:latest
WARNING: Image for service app was built because it did not already exist. To rebuild this image you must use `docker-compose build` or `docker-compose up --build`.
Creating sof_app_1 ... done
Attaching to sof_app_1
app_1  | total 8
app_1  | drwxr-xr-x    3 root     root            96 Feb 12 20:50 .
app_1  | drwxr-xr-x    1 root     root          4096 Feb 12 21:25 ..
app_1  | -rw-r--r--    1 root     root            45 Feb 12 20:51 tst.txt
app_1  | cat: can't open 'test.txt': No such file or directory
sof_app_1 exited with code 1

输出显示text.txt已复制到容器中,但是在主机上不可见。为什么会这样?

https://docs.docker.com/compose/faq/

  

“您可以使用COPY使映像包含代码,并在开发过程中使用Compose文件中的卷包含来自主机的代码。该卷将覆盖映像的目录内容。”

我将最后一句话解释为主机卷中的任何文件或文件夹都将覆盖映像映射目录中相同名称的文件或文件夹。我不希望主机目录完全覆​​盖映像的目录,删除其中已存在的任何文件。我对这个假设有误吗?

任何好的指导都值得赞赏。

1 个答案:

答案 0 :(得分:1)

绑定的卷完全覆盖了您在撰写文件中指定的目录,因此您不会看到dockerfile在/ app目录中复制任何文件。

您必须使用匿名卷或命名卷,以便docker在挂载之前复制声明的卷中的文件。 [1]

如果您仍要使用绑定挂载的卷,则唯一的选择是一旦容器已启动(不在dockerfile上)复制文件。

[1] https://docs.docker.com/engine/reference/builder/#volume

相关问题