Docker and iptables firewall

Docker works perfectly fine when no firewall is running on the host machine. Without the firewall docker containers can communicate with each other and with the outside world. But with the firewall we need to setup some rules in order to allow traffic to and from the docker interface. Below it is detailed how we can configure the firewall for docker on a Centos server.

First of all let us find the docker interface and IP, we can do that using the ifconfig command:

Here the interface name is docker0. Now we can setup firewall rules using the iptables command:

# Enable masquerading and allow connections to containers
iptables -t nat -A POSTROUTING -s 172.17.0.0/16 ! -o docker0 -j MASQUERADE
iptables -t filter -A FORWARD -o docker0 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT

# Allow internal and external container communication
iptables -t filter -A FORWARD -i docker0 ! -o docker0 -j ACCEPT
iptables -t filter -A FORWARD -i docker0 -o docker0 -j ACCEPT

With these rules setup, Docker containers can now talk to each other and the outside world.

If you use CSF (Config Server Firewall), a custom chain with these rules can be added to csfpost.sh file, like below:

#!/bin/sh

echo "[DOCKER] Setting up firewall rules."

# Create a new chain
iptables -N DOCKER
iptables -A FORWARD -o docker0 -j DOCKER

# Enable masquerading and allow connections to containers
iptables -t nat -A POSTROUTING -s 172.17.0.0/16 ! -o docker0 -j MASQUERADE
iptables -t filter -A FORWARD -o docker0 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT

# Allow internal and external container communication
iptables -t filter -A FORWARD -i docker0 ! -o docker0 -j ACCEPT
iptables -t filter -A FORWARD -i docker0 -o docker0 -j ACCEPT

iptables -A DOCKER -j RETURN

echo "[DOCKER] Done."

And then reload the firewall rules using the command below:

csf -r

3 Comments

hi there

really nice post. thanks for that.

how can i specify the gateway for my containers? i want to route the container traffic via a private_ip NIC. or certain outgoing connections to internal ip’s (from containers) need to go via the private ip nic. any idea how i could archive this via IPTABLES?

Leave a Reply