May 22, 2021 Docker From entry to practice
By default, containers can actively access connections to external networks, but external networks cannot access containers.
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.
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:
-p IP:host_port:container_port
or
-p IP::port
to establish stricter rules.
DOCKER_OPTS="--ip=IP_ADDRESS"
in the Docker profile
/etc/default/docker
after which the restart of the Docker service takes effect.