共享 docker 卷挂载主机目录

时间:2021-04-08 15:02:07

标签: docker-volume

我喜欢在我的主机上挂载一个特定目录和两个容器。一切都在 docker-compose.yaml 文件中定义。

在 yaml 文件的 services 部分,对于两个容器,指定了以下内容:

volumes:
- myvolume:/internal/path

在volume部分,volume定义为:

volumes:
    myvolume:
        driver: local

默认情况下,共享卷作为单个文件位于 /var/libs/docker/volumes 中。现在,我想在主机的文件系统中指定一个目录,比如说目录 /host/directory。有人可以说明如何通过 docker-compose 实现这一点吗?

1 个答案:

答案 0 :(得分:0)

与 docker 服务共享主机卷是通过在服务部分指定卷来完成的,如下所示:

# ...
    volumes:
      - /path/in/host:/path/in/service
# ...

多个服务可能使用同一个主机卷。

举一个更完整的例子,一个 docker-compose.yaml 将一个 Linux 主机目录挂载到多个 docker 服务中,例如看起来像这样:

version: "3.3"
services:
  service_1:
    image: alpine
    volumes:
      - ./shared_host_directory:/path/in/service_1
    command: >
      /bin/sh -c "echo 'A message from service 1' >> /path/in/service_1/output.log"

  service_2:
    image: alpine
    volumes:
      - ./shared_host_directory:/path/in/service_2
    command: >
      /bin/sh -c "echo 'A message from service 2' >> /path/in/service_2/output.log"

如果您使用以下命令执行此示例

mkdir -p shared_host_directory  # Make sure that the shared host directory exists.
rm -rf shared_host_directory/output.log  # Make sure that the output file does not exist yet.
docker-compose up  # Execute the docker-compose.yaml file until both services terminate.
cat shared_host_directory/output.log  # Get the output of the created log file.

那么shared_host_directory/output.log的显示内容应该是这样的:

A message from service 1
A message from service 2

请注意,由于服务 1 和 2 之间的竞争条件,线路可能会切换。 当然,您也可以将 docker-compose.yaml 中的相对路径替换为绝对路径。

引用 docker compose 文件参考,https://docs.docker.com/compose/compose-file/compose-file-v3/#volumes

<块引用>

您可以挂载一个主机路径作为单个定义的一部分 服务,不需要在顶级volumes中定义 键。

请注意,上面的链接还包含有关使用 docker-compose 的卷的更多示例。