如何一次性定义Bind Mount并在多个Docker容器中复用?
能否一次性定义Bind Mount并在多个Docker容器中复用?
我需要在开发机上启动多个Docker容器,并将宿主机上的一个文件夹挂载到所有容器中。我知道可以一次性创建Volume并在多个挂载命令中复用,但不清楚能否一次性定义Bind Mount并复用。
复用Volume的有效方式:
docker volume create not-what-i-need docker run -d -t \ --name container1 \ --mount source=not-what-i-need, target=/home/appuser/abc \ image1 docker run -d -t \ --name container2 \ --mount source=not-what-i-need, target=/home/appuser/abc \ image2
我想要实现的Bind Mount复用效果(当前需重复写挂载参数,希望能一次性定义后复用):
docker run -d -t \ --name container1 \ --mount type=bind,source=/host-machine/folder1, target=/home/appuser/abc \ image1 docker run -d -t \ --name container2 \ --mount type=bind, source=/host-machine/folder1, target=/home/appuser/abc \ image2
Docker本身没有提供像docker volume create那样预先创建可复用Bind Mount对象的机制,但可以通过以下几种方法实现复用Bind Mount配置的效果:
使用环境变量统一管理
把Bind Mount的完整参数定义成环境变量,后续启动容器时直接引用,避免重复输入路径:# 定义环境变量 export MY_BIND_MOUNT="type=bind,source=/host-machine/folder1,target=/home/appuser/abc" # 启动容器1 docker run -d -t --name container1 --mount $MY_BIND_MOUNT image1 # 启动容器2 docker run -d -t --name container2 --mount $MY_BIND_MOUNT image2用Docker Compose复用挂载配置
如果使用Docker Compose,可以通过锚点(&)和合并(<<)语法复用挂载规则,减少重复代码:version: '3.8' # 定义可复用的挂载锚点 x-common-mounts: &common-mounts volumes: - /host-machine/folder1:/home/appuser/abc services: container1: image: image1 tty: true <<: *common-mounts container2: image: image2 tty: true <<: *common-mounts编写Shell脚本封装逻辑
把容器启动逻辑写到脚本里,挂载参数只定义一次,脚本内多次调用启动命令:#!/bin/bash # 定义挂载参数 BIND_MOUNT="type=bind,source=/host-machine/folder1,target=/home/appuser/abc" # 启动容器1 docker run -d -t --name container1 --mount $BIND_MOUNT image1 # 启动容器2 docker run -d -t --name container2 --mount $BIND_MOUNT image2
内容的提问来源于stack exchange,提问作者ThrowableException
相关产品推荐
相关产品推荐

