Method of Docker Dynamic Modifying Container Port Mapping

  • 2021-10-13 09:07:56
  • OfStack

Docker port mapping is usually to map the internal port of the container to the designated port of the host machine through-p when Docker Run command. Generally speaking, the port corresponding to the port of the container is determined in advance and needs to be mapped. However, in some cases, it is necessary to temporarily map ports. For example, MySQL container is running in Docker, and the default port is not open. So is there any way to expose the specified port for the running container? My guest, please look down- >

Method 1: Change the Docker configuration file (risky)

This is accomplished by modifying the configuration file for Docker, 1 which generally requires modifications to the following files config. v2. json and hostconfig. json. The default path is /var/lib/docker/containers/<容器名称> .

Pass first systemctl stop docker Shut down the Docker service, then modify the ExposedPorts configuration information in the config. v2.json file to add container internal ports such as "8080/tcp": {}, and then modify the PortBindings configuration information in hostconfig. json as shown below.

After completing the above configuration, systemctl restart docker Restart the docker service and restart the specified container to access the corresponding port. (This method is risky and not recommended for frequent use)


 "Config": {
  "ExposedPorts": {
   //  Add an internal port 5432 Mapping 
   "5432/tcp": {},
   "8080/tcp": {}
  },s
  ...
 },

"PortBindings":{
  //  Add internal ports and external ports 15432
  "5432/tcp":[
   {
    "HostIp":"",
    "HostPort":"15432"
   }
  ],
  "8080/tcp":[
   {
    "HostIp":"",
    "HostPort":"28080"
   }
  ]
 },

Method 2: Iptables port forwarding

The network port mapping principle of Docker is to realize port forwarding through Iptables. Based on this principle, we can directly use iptables to forward ports to the target container Ip. Port forwarding can be realized by the following command. This method depends on the rules of Iptables, which may lead to the conflict of rules of Iptables in some scenarios, thus affecting the effective startup of containers.


#  Port mapping 
iptables -t nat -A DOCKER -p tcp --dport < Container external port > -j DNAT --to-destination < Container ip>:< Container internal port >
#  Cancel port mapping rules 
iptables -t nat -D DOCKER -p tcp -d 0/0 --dport < Container external port > -j DNAT --to-destination < Container ip>:< Container internal port >

Related articles: