【问题标题】:Shared docker volume mounts host directory共享 docker 卷挂载主机目录
【发布时间】:2021-07-04 11:39:21
【问题描述】:

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

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

volumes:
- myvolume:/internal/path

在volume部分,volume定义为:

volumes:
    myvolume:
        driver: local

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

【问题讨论】:

    标签: docker-volume


    【解决方案1】:

    通过在服务部分中指定卷来与 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 的卷的更多示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-19
      • 2017-04-15
      • 1970-01-01
      • 2018-10-09
      • 1970-01-01
      • 2017-06-30
      相关资源
      最近更新 更多