Docker with firewall on host-exposed system

Using docker can be a pain as it interferes with your firewall settings. This can be seen when using ufw, as the docker ports will still be exposed without allowance in ufw. This happens because docker changes the iptables rule directly itself. To fix this I searched a while a tried out different things like the ufw-docker tool, but the following helped me most and is the easiest way.

Adding the following to /etc/ufw/after.rules helps to remove the hole-punching of docker on systems using ufw as firewall:

# BEGIN UFW AND DOCKER
*filter
:ufw-user-forward - [0:0]
:DOCKER-USER - [0:0]
-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 -j ufw-user-forward

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

-A DOCKER-USER -j RETURN
COMMIT
# END UFW AND DOCKER

Credits: https://stackoverflow.com/a/51741599 This is not mentioned on the docker docs, which explains the iptables behavior: https://docs.docker.com/network/packet-filtering-firewalls/#docker-and-ufw