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

daB*_*bby 1 docker docker-compose

想象一下,我有一个包含一些静态数据的 Docker 容器。

现在出于开发目的,我希望将容器目录的内容/resources安装到我的本地工作目录.

docker-compose.yml:

version: '3.2'

services:
  resources:
    image: <private_registry>/resources:latest
    volumes:
    - ./resources:/resources
Run Code Online (Sandbox Code Playgroud)

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

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

BMi*_*tch 6

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

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

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

  # 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
  ...
Run Code Online (Sandbox Code Playgroud)

您的示例看起来更像是:

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
Run Code Online (Sandbox Code Playgroud)

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