如何在 docker 容器中使用 docker 卷中的文件

how to use files from a docker volume in a docker container

我想知道我是否可以通过许多 docker 个容器使用一个 docker 卷。 如果是,docker 卷是否已锁定?

您可以先创建一个命名卷,然后在任何您想要的地方使用它,一个或多个 dockers。

当您创建命名卷时,例如名为 myvolume,如果您不指定驱动程序选项,则使用 local。因此,docker 在 /var/lib/docker/volumes 中创建了一个文件夹。您的数据将保留在 /var/lib/docker/volumes/myvolume/_data

不过,那只是信息,您不需要管理它。您只需创建:

docker volume create myvolume

然后,使用卷名作为源。

docker run -v myvolume:/yourdestinationpath ...

如果使用docker compose,语法是一样的:

services:
  myservice:
    ...
    volumes: 
      - myvolume:/yourdestinationpath

关键是您没有使用 绑定卷 ,您在其中指定要安装的具体路径作为源,而是 docker 卷名称。

这是一个最小的示例,我在其中将本地目录挂载到容器中。我的本地目录将充当持久卷,我可以在其中从容器读取和写入。

我的当前目录包含一个input-file(这个文件应该被容器读取)
容器 cats input-file 的内容并将其附加到 output-file (这里我伪造你的 conversion)

// The initial wiorking directory content
.
└── input-file

// Read the `input-file` and append its content to the `output-file` (both files are persisted on the host machine)
docker run -v $(pwd):/root/some-path ubuntu /bin/bash -c "cat /root/some-path/input-file >> /root/some-path/output-file"

// The outcome
.
├── input-file
└── output-file