Docker has running container to add port mapping
Add port mapping for running containers
1. Check whether the container maps the port
docker port [容器id 或 容器名]
There is port mapping:
No port mapping:
2. View the complete ID of the container
docker inspect [容器id] | grep Id
// 得到以下结果
// "Id": "fcae55f5180a79487662de426863565c7df05ed9b87854093b62776734928d25",
3. Enter the docker container directory to view
cd /var/lib/docker/containers/var/lib/docker/containers
4. Enter the directory based on the complete container ID obtained.
cd fcae55f5180a79487662de426863565c7df05ed9b87854093b62776734928d25
There are two files in the directory: hostconfig.json
and config.v2.json
. Viewing the file content directly is confusing. You can download it to your local machine and use the json tool to view it.
5. Modify configuration file
hostconfig.json
// 当前容器 3306 端口绑定到本机 3306 端口
"PortBindings": {
"3306/tcp": [
{
"HostIp": "",
"HostPort": "3306"
}
]
},
config.v2.json
// 这个文件需要查看两个位置
// 暴露 3306、33060 端口
"ExposedPorts": {
"3306/tcp": {
},
"33060/tcp": {
}
},
// 和
// 这一段应该是表示哪些ip可以访问之类的
// 如下也是我从一个 docker run -d -p80:80 ... 带有端口映射的容器的 config.v2.json 文件中复制出来修改后的
"Ports": {
"3306/tcp": [
{
"HostIp": "0.0.0.0",
"HostPort": "3306"
},
{
"HostIp": "::",
"HostPort": "3306"
}
],
"33060/tcp": null
},
6. Replace configuration file
-
Stop container
docker stop [容器Id 或 容器名]
-
Copy the modified configuration file to the specified directory
/var/lib/docker/containers/完整容器Id
(you can back up the original file first if you are afraid of making mistakes) -
Restart docker
systemctl restart docker
-
After restarting, you can first check whether the
hostconfig.json
andconfig.v2.json
configuration files have been modified. If not, you can try uploading them a few more times (this is what happened to me). -
Finally, check whether the port number is mapped
docker port [容器id 或 容器名称]