gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 21:14:26 26 4
gpt4 key购买 nike

假设我有一个包含一些静态数据的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com