1. 前言
docker
启动前是image
文件,启动后是container
文件,启动的时候我们可以指定容器的挂载目录以及网络类型,但启动后,这些信息都以配置文件的形式保存在container
中,container
重新启动时无法重新指定这些信息,这些文件可以修改,但需要停止容器以及容器服务的运行,并需要按照既定的格式进行修改。
2. 查看配置文件
- 创建三个容器,容器0不挂载目录,容器1挂载1个目录,容器挂载3个目录,分别对比它们的配置文件。
# 此处使用-itd参数,容器启动会自动后台运行,之后可以使用"docker attach"进入容器交互,主机的目录可以不存在,docker会自动创建
$ docker run -itd --name test0 ubuntu_base
$ docker run -itd --name test1 -v ./test1:/test1 ubuntu_base
$ docker run -itd --name test2 -v ./test1:/test1 -v ./test2:/test2 ubuntu_base
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
a9a40a34abad ubuntu_base "/bin/bash" 8 seconds ago Up 3 seconds test2
3ed594b52a9e ubuntu_base "/bin/bash" 20 seconds ago Up 15 seconds test1
718b9c1d54c6 ubuntu_base "/bin/bash" 50 seconds ago Up 40 seconds test0
docker inspect
可以查看一些底层的信息。
# 查看test0的信息,其中可以看到一些path路径,‘/var/lib/docker/containers/’开头的就是容器的配置文件路径,该路径需要管理员权限来访问
$ docker inspect test0
...
"ResolvConfPath": "/var/lib/docker/containers/718b9c1d54c6089d4294627c1661657a77072aa378d269ba0a7bfa906f2e40eb/resolv.conf",
...
# 查看该目录下的所有文件,我们主要关注config.v2.json和hostconfig.json文件
$ sudo ls /var/lib/docker/containers/718b9c1d54c6089d4294627c1661657a77072aa378d269ba0a7bfa906f2e40eb/
718b9c1d54c6089d4294627c1661657a77072aa378d269ba0a7bfa906f2e40eb-json.log
config.v2.json
hostname
mounts
resolv.conf.hash
checkpoints
hostconfig.json
hosts
resolv.conf
- 安装
jq
工具,它是一个json
的读写工具,稍后我们使用它格式化docker
命令的输出。
$ sudo apt install jq
# hostconfig.json是挤在一行,没有缩进的,不便于查看,可以使用"jq"工具进行格式化
$ sudo cat /var/lib/docker/containers/718b9c1d54c6089d4294627c1661657a77072aa378d269ba0a7bfa906f2e40eb/hostconfig.json | jq
# python也自带有json工具,下面这种方式也能实现json的格式化输出
$ sudo cat /var/lib/docker/containers/718b9c1d54c6089d4294627c1661657a77072aa378d269ba0a7bfa906f2e40eb/hostconfig.json | python3 -m json.tool
- 将三个容器的
hostconfig.json
配置文件进行对比,可以看出其中的区别。
- 将三个容器的
config.v2.json
配置文件进行对比,可以看出其中的区别。
3. 修改挂载的脚本
python比较适合处理json文件,此处就编写一个python脚本文件docker_path.py
,用于向容器中新增挂载的目录或文件,删除的挂载目录的动作不常用就不实现了。
#!/usr/bin/python3import json
import os
import subprocess
import sys# json类型 python类型
# 对象{} 字典{}
# 数组[] 列表[]# 打印帮助信息,不返回
def usage() -> object:print("docker_path [docker name] [host-path:docker-path]")exit(-1)# 检测当前脚本是否具有管理员权限
if os.getuid() != 0:# 重新使用sudo执行脚本,终端会自动提示输入密码subprocess.run(['sudo'] + sys.argv)exit()# 判断参数个数,第0个参数是脚本本身
if len(sys.argv) != 3:print("Two parameters are required")usage()# 第1个参数是容器名称
docker_name = sys.argv[1]
# 此处未指定shell,因此需要将程序和每个参数都分开成列表项
# stdout=subprocess.PIPE表示程序的标准输出重定向到ret中
# stderr=subprocess.DEVNULL表示将程序的标准错误输出丢弃
ret = subprocess.run(['docker', 'inspect', '-f', 'json', '--type', 'container', docker_name], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
# 若容器不存在,则返回1
if ret.returncode != 0:print('Container [' + docker_name + '] isn\'t exist')usage()# 将docker inspect的输出转换为python对象
inspect = json.loads(ret.stdout)# 提取参数中的路径信息,使用‘:’分割
dir_idx = sys.argv[2].find(':')
# 未找到':'即错误
if dir_idx == -1:print(sys.argv[2] + ' should be in "host-path:docker-path" format')usage()# 提取主机路径和容器路径
host_dir = os.path.abspath(sys.argv[2][:dir_idx])
docker_dir = sys.argv[2][dir_idx + 1:]# 主机路径不存时,容器启动后会自行创建, 此处仅打印警告,不退出
if os.path.exists(host_dir) == False:print('Host path [' + sys.argv[2][:dir_idx] + '] isn\'t exist')#usage()# [0]表示列表中的第一个元素
# ['HostsPath']表示字典中的键值HostsPath
# 使用os.path.dirname提取配置文件的目录
conf_path = os.path.dirname(inspect[0]['HostsPath']) + '/'# 判断容器是否正在运行
if inspect[0]['State']['Status'] == 'running':# 正在运行的容器需要先停止kill = input('Docker [' + docker_name + '] is running, do you want to stop [yes/no]: ')if kill == 'yes':print('It takes some time to close the container')if os.system('docker stop ' + docker_name) != 0:print('Docker stop error, exit')exit()else:print('Exit with nothing')exit()# 判断当前运行中的容器数量
ret = subprocess.run(['docker', 'info', '-f', 'json'], stdout=subprocess.PIPE)
if ret.returncode == 0:info = json.loads(ret.stdout)# 如果有其他容器正在运行,则退出if info['ContainersRunning'] != 0:print('Other containers are running, please close them and try again, exit')exit()# 停止docker服务,停止后不需要手动开启,执行docker命令时会自动开启,该动作需要管理员权限
ret = subprocess.run(['systemctl', 'stop', 'docker'], stderr=subprocess.DEVNULL)
if ret.returncode != 0:print('Stop docker service error, exit')exit()# 读取容器的config.v2.json配置文件,该动作需要管理员权限
with open(conf_path + 'config.v2.json', 'r', encoding='utf-8') as f:config = json.load(f)# 备份要修改的文件,如果脚本运行失败,则需要手动恢复一下,否者容器可能无法在docker ps -a中查看到
os.replace(conf_path + 'config.v2.json', conf_path + 'config.v2.json.bak')# 向MountPoints字典中添加一个目录映射
config['MountPoints'][docker_dir] = {'Source': host_dir,'Destination': docker_dir,'RW': True,'Name': '','Driver': '','Type': 'bind','Propagation': 'rprivate','Spec': {'Type': 'bind','Source': host_dir,'Target': docker_dir,},'SkipMountpointCreation': False,
}# 写入容器的config.v2.json配置文件,该动作需要管理员权限
with open(conf_path + 'config.v2.json', 'w', encoding='utf-8') as f:json.dump(config, f)# 读取容器的hostconfig.json配置文件,该动作需要管理员权限
with open(conf_path + 'hostconfig.json', 'r', encoding='utf-8') as f:config = json.load(f)# 备份要修改的文件,如果脚本运行失败,则需要手动恢复一下,否者容器可能无法在docker ps -a中查看到
os.replace(conf_path + 'hostconfig.json', conf_path + 'hostconfig.json.bak')# 当容器没有绑定过目录时,该键值是null,对应python的None,需要使用'=',当有
# 过绑定时,该键值有值是json的数组,对应python的列表,使用'+='
if config['Binds'] is None:config['Binds'] = [host_dir + ':' + docker_dir]
else:config['Binds'] += [host_dir + ':' + docker_dir]# 写入容器的hostconfig.json配置文件,该动作需要管理员权限
with open(conf_path + 'hostconfig.json', 'w', encoding='utf-8') as f:json.dump(config, f)
4. 修改网络的脚本
根据上面的经验编写一个修改网络类型的脚本docker_net.py
。
#!/usr/bin/python3import json
import os
import subprocess
import sys# json类型 python类型
# 对象{} 字典{}
# 数组[] 列表[]# 打印帮助信息,不返回
def usage() -> object:print("docker_net [docker name] [host/bridge]")exit(-1)# 检测当前脚本是否具有管理员权限
if os.getuid() != 0:# 重新使用sudo执行脚本,终端会自动提示输入密码subprocess.run(['sudo'] + sys.argv)exit()# 判断参数个数,第0个参数是脚本本身
if len(sys.argv) != 3:print("Two parameters are required")usage()# 第1个参数是容器名称
docker_name = sys.argv[1]
# 此处未指定shell,因此需要将程序和每个参数都分开成列表项
# stdout=subprocess.PIPE表示程序的标准输出重定向到ret中
# stderr=subprocess.DEVNULL表示将程序的标准错误输出丢弃
ret = subprocess.run(['docker', 'inspect', '-f', 'json', '--type', 'container', docker_name], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
# 若容器不存在,则返回1
if ret.returncode != 0:print('Container [' + docker_name + '] isn\'t exist')usage()# 将docker inspect的输出转换为python对象
inspect = json.loads(ret.stdout)# 第2个参数是host或bridge表示要修改的类型
docker_net = sys.argv[2]
if docker_net not in ['host', 'bridge']:print('Network [' + docker_net + '] is not support, exit')usage()# [0]表示列表中的第一个元素
# ['HostsPath']表示字典中的键值HostsPath
# 使用os.path.dirname提取配置文件的目录
conf_path = os.path.dirname(inspect[0]['HostsPath']) + '/'# 读取容器的hostconfig.json配置文件,该动作需要管理员权限
with open(conf_path + 'hostconfig.json', 'r', encoding='utf-8') as f:config = json.load(f)# 判断网络类型是否需要修改
if config['NetworkMode'] == docker_net:print('Network doesn\'t need change, do nothing')exit()
# 记录老的网络模型
docker_net_old = config['NetworkMode']# 判断容器是否正在运行
if inspect[0]['State']['Status'] == 'running':# 正在运行的容器需要先停止kill = input('Docker [' + docker_name + '] is running, do you want to stop [yes/no]: ')if kill == 'yes':print('It takes some time to close the container')if os.system('docker stop ' + docker_name) != 0:print('Docker stop error, exit')exit()else:print('Exit with nothing')exit()# 判断当前运行中的容器数量
ret = subprocess.run(['docker', 'info', '-f', 'json'], stdout=subprocess.PIPE)
if ret.returncode == 0:info = json.loads(ret.stdout)# 如果有其他容器正在运行,则退出if info['ContainersRunning'] != 0:print('Other containers are running, please close them and try again, exit')exit()# 停止docker服务,停止后不需要手动开启,执行docker命令时会自动开启,该动作需要管理员权限
ret = subprocess.run(['systemctl', 'stop', 'docker'], stderr=subprocess.DEVNULL)
if ret.returncode != 0:print('Stop docker service error, exit')exit()# 备份要修改的文件,如果脚本运行失败,则需要手动恢复一下,否者容器可能无法在docker ps -a中查看到
os.replace(conf_path + 'hostconfig.json', conf_path + 'hostconfig.json.bak')# 修改网络类型,之前已经读取过hostconfig.json,此处不在重新读取
config['NetworkMode'] = docker_net# 写入容器的hostconfig.json配置文件,该动作需要管理员权限
with open(conf_path + 'hostconfig.json', 'w', encoding='utf-8') as f:json.dump(config, f)# 读取容器的config.v2.json配置文件,该动作需要管理员权限
with open(conf_path + 'config.v2.json', 'r', encoding='utf-8') as f:config = json.load(f)# 备份要修改的文件,如果脚本运行失败,则需要手动恢复一下,否者容器可能无法在docker ps -a中查看到
os.replace(conf_path + 'config.v2.json', conf_path + 'config.v2.json.bak')# 向Networks字典中更换键名
config['NetworkSettings']['Networks'][docker_net] = config['NetworkSettings']['Networks'].pop(docker_net_old)# 写入容器的config.v2.json配置文件,该动作需要管理员权限
with open(conf_path + 'config.v2.json', 'w', encoding='utf-8') as f:json.dump(config, f)
5. 定义命令别名
将docker_path.py
和docker_net.py
放到~/tools/python/
目录下,并设置可执行权限,修改~/tools/tools.sh
,增加别名定义。
# 设置文件可执行权限
$ chmod +x docker_path.py docker_net.py
# 定义别名
$ alias docker_path="~/tools/python/docker_path.py"
$ alias docker_net="~/tools/python/docker_net.py"
6. 过程中的问题
- python脚本中不能使用
\r\n
换行,否者直接在Linux的shell中执行会报错。
# 在脚本所在目录执行py脚本
$ ./docker_path.py
-bash: ./docker_path.py: cannot execute: required file not found
# 使用vim -b打开文件可以看到每行尾都有^M,即为\r,使用":s/\r//g"即可删除所有\r
$ vi -b docker_path.py
#!/usr/bin/python3^M
...
- 关闭docker服务时,会报警告,这句话意思是docker服务已停止,但是socket仍然在运行,后续执行docker命令时会自动启动docker服务。
$ sudo systemctl stop docker
Stopping 'docker.service', but its triggering units are still active:
docker.socket
上一篇:docker(1) – centos镜像
下一篇:docker(2) – 启动后修改目录和网络
目录:文章合集