Console9

How to fix Docker bypassing UFW firewall rules

Prevent Docker from exposing container ports to the public internet by bypassing UFW on Ubuntu.

Prevent Docker from circumventing UFWfirewall rules by binding containers to localhost or configuring the DOCKER-USER iptables chain.

Step-by-Step: Fix Docker Bypassing UFW

1. Bind Container Ports to localhost Only

Restrict Docker port mappings to the loopback interface:

docker run -p 127.0.0.1:3306:3306 mysql:8

In Docker Compose:

ports:
  - "127.0.0.1:3306:3306"

The port is accessible only from the host machine, not from the public internet.

2. Add Restrictive Rules to DOCKER-USER Chain

The DOCKER-USER iptables chain is evaluated before Docker's own rules:

sudo iptables -I DOCKER-USER -i eth0 -j DROP
sudo iptables -I DOCKER-USER -i eth0 -s 203.0.113.50 -j ACCEPT

This drops all external traffic to Docker containers except from the specified IP address.

3. Persist the iptables Rules

sudo apt install iptables-persistent
sudo netfilter-persistent save

See UFW: Docker bypasses UFW rulesfor the detailed explanation.