Uncomplicated Firewall / Docker Workaround

To get UFW to work well with Docker, you have to add some rules to the bottom of

/etc/ufw/after.rules

# BEGIN UFW AND DOCKER
*filter
:ufw-user-forward - [0:0]
:ufw-docker-logging-deny - [0:0]
:DOCKER-USER - [0:0]
-A DOCKER-USER -j ufw-user-forward

-A DOCKER-USER -j RETURN -s 10.0.0.0/8
-A DOCKER-USER -j RETURN -s 172.16.0.0/12
-A DOCKER-USER -j RETURN -s 192.168.0.0/16

-A DOCKER-USER -p udp -m udp --sport 53 --dport 1024:65535 -j RETURN

-A DOCKER-USER -j ufw-docker-logging-deny -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -d 192.168.0.0/16
-A DOCKER-USER -j ufw-docker-logging-deny -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -d 10.0.0.0/8
-A DOCKER-USER -j ufw-docker-logging-deny -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -d 172.16.0.0/12
-A DOCKER-USER -j ufw-docker-logging-deny -p udp -m udp --dport 0:32767 -d 192.168.0.0/16
-A DOCKER-USER -j ufw-docker-logging-deny -p udp -m udp --dport 0:32767 -d 10.0.0.0/8
-A DOCKER-USER -j ufw-docker-logging-deny -p udp -m udp --dport 0:32767 -d 172.16.0.0/12

-A DOCKER-USER -j RETURN

-A ufw-docker-logging-deny -m limit --limit 3/min --limit-burst 10 -j LOG --log-prefix "[UFW DOCKER BLOCK] "
-A ufw-docker-logging-deny -j DROP

COMMIT

Adding Rules

Then you can add rules. Always add rules with comments. Examples below:

# Opening non-docker ports:

## To specific IP

ufw allow from x.x.x.x to any port 81 comment "NPM Admin"

## To ALL IPs

ufw allow proto tcp from any to any port 1986 comment "SSH"

# Opening Docker container ports:

## To specific IP

ufw route allow proto tcp from x.x.x.x to any port 9001 comment "Portainer"
ufw route allow proto tcp from x.x.x.x. to any port 81 comment "NPM Admin"

## To ALL IPs

ufw route allow proto tcp from any to any port 3000 comment "Seafile"
ufw route allow proto tcp from any to any port 22 comment "Endlessh"

Show active rules with

ufw status

Reference(s):

Leave a Comment