[英]How to mount Docker directory into host directory with docker-compose
Imagine I have a Docker container containing some static data.想象一下,我有一个包含一些静态数据的 Docker 容器。
Now for development purpose I want the content of the container directory /resources
mounted to my local working directory .
现在出于开发目的,我希望将容器目录/resources
的内容安装到我的本地工作目录.
. .
docker-compose.yml: docker-compose.yml:
version: '3.2'
services:
resources:
image: <private_registry>/resources:latest
volumes:
- ./resources:/resources
When running docker-compose up
the folder resources
is created in my working directory, bur it has no content, whereas the container has content in /resources/
运行docker-compose up
,文件夹resources
在我的工作目录中创建,但它没有内容,而容器在/resources/
中有内容
When using a named volume and inspecting it, it works like expected.使用命名卷并检查它时,它按预期工作。
Docker provides initialization of the the volume source to the content of your image in a specific scenario: Docker 在特定场景中为您的图像内容提供卷源的初始化:
You are currently stuck at the first requirement, but it is possible to map any folder from the host into the container using a named volume that performs a bind mount.您目前停留在第一个要求上,但是可以使用执行绑定安装的命名卷将任何文件夹从主机映射到容器中。 Here are some examples of three different ways to do that:以下是执行此操作的三种不同方法的一些示例:
# 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
...
Your example would look more like:您的示例看起来更像是:
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
Note that this directory must exist on the host in advance.注意这个目录必须事先存在于主机上。 The bind mount will fail without it, and unlike a host mount, docker will not create it for you.如果没有它,绑定挂载将失败,并且与主机挂载不同,docker 不会为您创建它。
There are a couple of things here.这里有几件事。 First, when you mount a host directory it 'shades' any existing content on the given path, effectively replacing it with the contents of the mount.首先,当您挂载主机目录时,它会“遮蔽”给定路径上的任何现有内容,有效地将其替换为挂载的内容。 So, your resources directory on your host is hiding any content in your container.因此,主机上的资源目录隐藏了容器中的任何内容。
There is no easy solution to your problem.您的问题没有简单的解决方案。 When I want to edit files in a container and on the host, I keep the files on the host and mount them in the container.当我想在容器和主机上编辑文件时,我将文件保存在主机上并将它们挂载到容器中。 If I want a copy of a container, I mount a host dir to a different dir in the container and arrange for the files to be copied.如果我想要一个容器的副本,我将一个主机目录挂载到容器中的另一个目录并安排要复制的文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.