Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Docker port mapping implementation


May 22, 2021 Docker From entry to practice



By default, containers can actively access connections to external networks, but external networks cannot access containers.

The container accesses the external implementation

For all connections from the container to the external network, the source address is the IP address of the NAT cost system. This is done using the source address spoofing operation of iptables

View the host's NAT rules.

$ sudo iptables -t nat -nL
...
Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination
MASQUERADE  all  --  172.17.0.0/16       !172.17.0.0/16
...

Among them, the above rules will be all the source 172.17.0.0/16 the target address for other segments (external network) traffic dynamically disguised as from the system network card issued. The advantage of MASQUERADE and traditional SNAT is that it dynamically gets addresses from network cards.

The external access container implementation

Containers allow external access and can be enabled by -p -P docker run

Either way, it's actually adding rules to the nat table of the local iptable

When -P

$ iptables -t nat -nL
...
Chain DOCKER (2 references)
target     prot opt source               destination
DNAT       tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:49153 to:172.17.0.2:80

With -p 80:80

$ iptables -t nat -nL
Chain DOCKER (2 references)
target     prot opt source               destination
DNAT       tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:80 to:172.17.0.2:80

Attention:

  • The rule here maps 0.0.0.0, which means that the host traffic from all interfaces will be accepted. Users can specify IP, interfaces, and so on on hosts that allow access to containers through -p IP:host_port:container_port or -p IP::port to establish stricter rules.
  • If you want to bind permanently to a fixed IP address, you can specify DOCKER_OPTS="--ip=IP_ADDRESS" in the Docker profile /etc/default/docker after which the restart of the Docker service takes effect.