Steps for limiting outside connections to docker container with iptables?

Two things to bear in mind when working with docker's firewall rules:

  1. To avoid your rules being clobbered by docker, use the DOCKER-USER chain
  2. Docker does the port-mapping in the PREROUTING chain of the nat table. This happens before the filter rules, so --dest and --dport will see the internal IP and port of the container. To access the original destination, you can use -m conntrack --ctorigdstport.

For example:

iptables -A DOCKER-USER -i eth0 -s 8.8.8.8 -p tcp -m conntrack --ctorigdstport 3306 --ctdir ORIGINAL -j ACCEPT
iptables -A DOCKER-USER -i eth0 -s 4.4.4.4 -p tcp -m conntrack --ctorigdstport 3306 --ctdir ORIGINAL -j ACCEPT
iptables -A DOCKER-USER -i eth0 -p tcp -m conntrack --ctorigdstport 3306 --ctdir ORIGINAL -j DROP

NOTE: Without --ctdir ORIGINAL, this would also match the reply packets coming back for a connection from the container to port 3306 on some other server, which is almost certainly not what you want! You don't strictly need this if like me your first rule is -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT, as that will deal with all the reply packets, but it would be safer to still use --ctdir ORIGINAL anyway.


With Docker v.17.06 there is a new iptables chain called DOCKER-USER. This one is for your custom rules: https://docs.docker.com/network/iptables/

Unlike the chain DOCKER it is not reset on building/starting containers. So you could add these lines to your iptables config/script for provisioning the server even before installing docker and starting the containers:

-N DOCKER
-N DOCKER-ISOLATION
-N DOCKER-USER
-A DOCKER-ISOLATION -j RETURN
-A DOCKER-USER -i eth0 -p tcp -m tcp --dport 3306 -j DROP
-A DOCKER-USER -j RETURN

Now the port for MySQL is blocked from external access (eth0) even thought docker opens the port for the world. (These rules assume, your external interface is eth0.)

Eventually, you will have to clean up iptables restart the docker service first, if you messed it too much trying to lock down the port as I did.