我想在码头集装箱之间共享单个文件。
ContainerA:
- file-1
- file-2
- file-3
- shared-file
ContainerB
- file-a
- file-b
- file-c
- shared-file我不可能分享一本完整的书。容器中的路径不一样。
发布于 2021-03-04 11:25:46
由于docker默认为卷目录,而且只有绑定-当源是现有文件时才挂载文件,所以使用起来有点困难。
对于您希望在当前目录中共享的file,可以在docker-compose.yml中使用绑定挂载。
services:
app1:
# ...
volumes:
- ./file:/path/to/file1:rw
app2:
# ...
volumes:
- ./file:/path/to/file2:rw这要求文件已经存在于容器之外。还请参阅朱本兹夫的回答中绑定挂载文件的注意事项。
根据您的用例,可能更好的解决方法是使用符号链接并将共享文件挂载到目录卷中:
# tree layout in containers:
ContainerA:
|- shared/
| ` shared-file
`- app_folder_a/
|- file-1
|- file-2
|- file-3
`- shared-file-a -> /shared/shared-file
ContainerB:
|- shared/
| ` shared-file
`- app_folder_b/
|- file-a
|- file-b
|- file-c
`- shared-file-b -> /shared/shared-file# docker-compose.yml
services:
app1:
# ...
volumes:
- ./shared/:/shared/:rw
app2:
# ...
volumes:
- ./shared/:/shared/:rw如果不希望/可以在主机上拥有文件或共享目录,则可以将命名卷与符号链接一起使用:
services:
app1:
# ...
volumes:
- shared:/app_folder_a
app2:
# ...
depends_on:
- app1
volumes:
- shared:/shared
volumes:
shared:以及在containerB中符号链接的共享文件:
ContainerB:
|- shared/
| ` ...
`- app_folder_b/
|- file-a
|- file-b
|- file-c
`- shared-file-b -> /shared/shared-file-a这里的重要部分是,在创建新卷shared时,第一次docker将使用容器中目标目录的内容对其进行预填充。因此,要正确工作,需要首先启动app1,以便shared卷中填充app_folder_a的内容--因此是depends_on。
这样,您就有了shared卷,其中填充了容器A的/app_folder_a/的内容,并安装到了相同的容器B的/shared/上,而/app_folder_b/shared-file-b是指向/shared/shared-file-a的符号链接。
发布于 2021-03-04 10:57:54
您可以使用卷来共享单个文件,而不是目录。但是在某些情况下,您不能正确地写入挂载的文件。
下面是一个很小的例子:
echo 'Test.' > /tmp/1.txt
docker run -it --user $(id -u):$(id -g) --rm -v /tmp/1.txt:/tmp/2.txt:rw alpine 在容器中,可以使用/tmp/1.txt路径从主机系统访问/tmp/2.txt:
/ $ cat /tmp/2.txt
Test.
/ $ echo '123' > /tmp/2.txt
/ $ cat /tmp/2.txt
123但是一些实用程序在写入文件时将尝试创建一个新的inode。例如:
/ $ cp etc/sysctl.conf /tmp/2.txt
cp: can't create '/tmp/2.txt': File exists重点是,将文件作为卷挂载在容器中的特定inode。一些修改文件的工具将inode替换为新的。但是您不能这样做,因为您挂载了指向文件的特定inode。
因此,您需要挂载一个目录,其中包含您可以在容器中修改的inode。有关更多信息,请参见码头数量文件。
发布于 2021-03-04 11:55:29
如果containerA在特定的路径上创建一个文件并覆盖符号链接,我认为用“干净”的方法(否则检查acran的答案)是不可能的。
我唯一能想到的办法是:
但是,也存在一些问题,例如,如果ContainerA崩溃了,那么ContainerB也需要重新创建,或者您需要再次复制文件。
如果将其包装在Makefile中,它可能如下所示:
.DEFAULT_GOAL := run
run:
docker-compose up -d containerA
sleep 10
docker cp containerA:/seed-file seed-file
docker-compose up -d containerBhttps://stackoverflow.com/questions/66473273
复制相似问题