docker - 如何使用 docker-compose 将 Docker 目录挂载到主机目录

标签 docker docker-compose

假设我有一个包含一些静态数据的 Docker 容器。

现在出于开发目的,我想将容器目录 /resources 的内容挂载到我的本地工作目录 .

docker-compose.yml:

version: '3.2'

services:
  resources:
    image: <private_registry>/resources:latest
    volumes:
    - ./resources:/resources

运行 docker-compose up 时,文件夹 resources 在我的工作目录中创建,但它没有内容,而容器在 /resources 中有内容/

使用命名卷并检查它时,它按预期工作。

最佳答案

Docker 在特定场景下为您的镜像内容提供卷源的初始化:

  • 它必须是命名卷,而不是主机卷(将路径映射到容器中)
  • volume source必须为空,一旦目录中有数据,docker将不会更改
  • 仅在创建容器时(容器运行时不会重新初始化文件夹)
  • 尚未设置禁用复制的选项(这是撰写文件中的“nocopy”选项)。

您目前停留在第一个要求,但可以使用执行绑定(bind)安装的命名卷将主机中的任何文件夹映射到容器中。以下是执行此操作的三种不同方法的一些示例:

  # create the volume in advance
  $ docker volume create --driver local \
      --opt type=none \
      --opt device=/home/user/test \
      --opt o=bind \
      test_vol

  # create on the fly with --mount
  $ docker run -it --rm \
    --mount type=volume,dst=/container/path,volume-driver=local,volume-opt=type=none,volume-opt=o=bind,volume-opt=device=/home/user/test \
    foo

  # inside a docker-compose file
  ...
  volumes:
    bind-test:
      driver: local
      driver_opts:
        type: none
        o: bind
        device: /home/user/test
  ...

你的例子看起来更像:

version: '3.2'

services:
  resources:
    image: <private_registry>/resources:latest
    volumes:
    - resources:/resources
volumes:
  resources:
    driver: local
    driver_opts:
      type: none
      o: bind
      device: /full/path/to/resources

注意这个目录必须事先在宿主机上存在。没有它,绑定(bind)挂载将失败,并且与主机挂载不同,docker 不会为您创建它。

关于docker - 如何使用 docker-compose 将 Docker 目录挂载到主机目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52152231/

相关文章:

docker - 使用 nginx 和 docker 测试本地子域

elasticsearch - Filebeats 不转发 Docker 撰写日志,为什么?

Docker-compose args 不会传递给 Dockerfile

php - 将 phpmailer V6 与 docker-compose 结合使用

Docker-compose 和 Docker-swarm

maven - 我无法建立red5-hls-plugin

jenkins - 我将如何在 CI 中创建包含大量服务的 docker 环境

docker - Traefik路径路由

macos - 使用 MacBookPro 主机在 docker 容器上运行 GUI 应用程序

docker - 如何使用 docker volume 命令创建的卷?