docker

Can't understand docker iptables rule


When using docker, we start with a image. And I created a container with docker.

docker run --name register -d -p 1180:5000 registry

iptables rules can be listed by running iptables-save:

# Generated by iptables-save v1.4.21 on Mon Oct 16 14:01:03 2017
*nat
:PREROUTING ACCEPT [129:14002]
:INPUT ACCEPT [129:14002]
:OUTPUT ACCEPT [25:1792]
:POSTROUTING ACCEPT [25:1792]
:DOCKER - [0:0]
-A PREROUTING -m addrtype --dst-type LOCAL -j DOCKER
-A OUTPUT ! -d 127.0.0.0/8 -m addrtype --dst-type LOCAL -j DOCKER
-A POSTROUTING -s 172.17.0.0/16 ! -o docker0 -j MASQUERADE
-A POSTROUTING -s 172.17.0.2/32 -d 172.17.0.2/32 -p tcp -m tcp --dport 5000 -j MASQUERADE
-A DOCKER -i docker0 -j RETURN
-A DOCKER ! -i docker0 -p tcp -m tcp --dport 1180 -j DNAT --to-destination 172.17.0.2:5000
COMMIT
# Completed on Mon Oct 16 14:01:03 2017
# Generated by iptables-save v1.4.21 on Mon Oct 16 14:01:03 2017
*filter
:INPUT ACCEPT [2721358:1990060388]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [2726902:1992988803]
:DOCKER - [0:0]
:DOCKER-ISOLATION - [0:0]
-A FORWARD -j DOCKER-ISOLATION
-A FORWARD -o docker0 -j DOCKER
-A FORWARD -o docker0 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A FORWARD -i docker0 ! -o docker0 -j ACCEPT
-A FORWARD -i docker0 -o docker0 -j ACCEPT
-A DOCKER -d 172.17.0.2/32 ! -i docker0 -o docker0 -p tcp -m tcp --dport 5000 -j ACCEPT
-A DOCKER-ISOLATION -j RETURN
COMMIT
# Completed on Mon Oct 16 14:01:03 2017

I don't understand this rule.

-A POSTROUTING -s 172.17.0.2/32 -d 172.17.0.2/32 -p tcp -m tcp --dport 5000 -j MASQUERADE

Solution

  • Best guess is that rule is to fix an edge case when you have the iptables POSTROUTING table defaulting to DENY any packets that don't match a rule, this allows connections from the container to itself on a mapped port through. In normal operation the rules do nothing functional.

    I think this is the pull request (#7003) that added the MASQ rule but there's no documentation as to why it was added. The commit was labeled "Create tests for pkg/iptables". The work was generally around fixing Docker on distro's that have default DENY tables.

    There is a suggestion in issue #12632 that the rule won't be touched unless the userland port mapping proxy is turned off.