UFW: Docker bypasses UFW rules
Fix Docker exposing container ports to the public internet by bypassing UFW firewall rules through direct iptables manipulation.
Docker modifies iptables directly to expose container ports, bypassing UFW's firewall rules entirely. A port blocked by UFW becomes publicly accessible when Docker maps it.
What Causes This
Docker adds rules to the
DOCKER and
DOCKER-USER iptables chains, which are evaluated before UFW's chains. When a container maps a port (
-p 3306:3306), Docker inserts an iptables rule that allows traffic to that port from any source — even if UFW has a deny rule.
How to Fix
Option 1: Bind Containers to localhost Only
Restrict Docker port mappings to the loopback interface so they are not publicly accessible:
docker run -p 127.0.0.1:3306:3306 mysql:8Option 2: Use the DOCKER-USER Chain
Add restrictive rules to the
DOCKER-USER iptables chain, which Docker evaluates before its own rules:
sudo iptables -I DOCKER-USER -i eth0 -p tcp --dport 3306 -j DROP
sudo iptables -I DOCKER-USER -i eth0 -s 203.0.113.50 -p tcp --dport 3306 -j ACCEPTOption 3: Disable Docker's iptables Management
Add
"iptables": false to
/etc/docker/daemon.json and restart Docker. This requires manual iptables/UFW configuration for all container networking.
Related
Docker troubleshootingfor container-specific network errors. UFW how-to guidesfor standard firewall configuration.