Blocking Outbound Docker Traffic

It’s possible to block outbound traffic from Docker containers using IPTables.

In this configuration, traffic will be allowed from the internet to docker instances, but the instances themselves will only be able to communicate with each other (provided they are using the docker0 interface).

Since I couldn’t find an tutorial to do this, I thought I would create a blog post. This should work on Ubuntu 20.04.

First, ensure that UFW is disabled:

ufw status
Status: inactive

Then install iptables-persistent service:

apt install iptables-persistent

Insert an iptables rule into the DOCKER-USER chain to REJECT outbound traffic:

iptables -I DOCKER-USER -d 0.0.0.0/0 -o docker0 -j REJECT

Note, the inbound connections to the docker image will still be allowed.

Verify the rules have been added correctly;

iptables -S DOCKER-USER
-N DOCKER-USER
-A DOCKER-USER -o docker0 -j REJECT --reject-with icmp-port-unreachable
-A DOCKER-USER -j RETURN

And finally, save the rules;

iptables-save > /etc/iptables/rules.v4