通过在服务部分中指定卷来与 docker 服务共享主机卷,如下所示:
# ...
volumes:
- /path/in/host:/path/in/service
# ...
多个服务可以使用相同的主机卷。
举一个更完整的例子,docker-compose.yaml 将 Linux 主机目录挂载到多个 docker 服务中,例如看起来像这样:
version: "3.3"
services:
service_1:
image: alpine
volumes:
- ./shared_host_directory:/path/in/service_1
command: >
/bin/sh -c "echo 'A message from service 1' >> /path/in/service_1/output.log"
service_2:
image: alpine
volumes:
- ./shared_host_directory:/path/in/service_2
command: >
/bin/sh -c "echo 'A message from service 2' >> /path/in/service_2/output.log"
如果您使用以下命令执行此示例
mkdir -p shared_host_directory # Make sure that the shared host directory exists.
rm -rf shared_host_directory/output.log # Make sure that the output file does not exist yet.
docker-compose up # Execute the docker-compose.yaml file until both services terminate.
cat shared_host_directory/output.log # Get the output of the created log file.
那么shared_host_directory/output.log 的显示内容应该是这样的:
A message from service 1
A message from service 2
请注意,由于服务 1 和 2 之间的竞争条件,可能会切换线路。
当然,你也可以将docker-compose.yaml中的相对路径替换为绝对路径。
引用 docker compose 文件参考,https://docs.docker.com/compose/compose-file/compose-file-v3/#volumes,
您可以挂载主机路径作为单个定义的一部分
服务,不需要在顶层volumes定义
键。
请注意,上面的链接还包含有关使用 docker-compose 的卷的更多示例。