Use iptables Instead of UFW with Docker
Recently I was installing docker when I came across some warnings in the documentation:

Docker’s documentation says:
Make sure that any firewall rulesets you use are created with
iptablesorip6tables, and that you add them to theDOCKER-USERchain, see Packet filtering and firewalls.
The gist of the security warning above is that Docker creates iptables rules itself, so it can bypass other firewall configurations. Be aware that ports you open with a container are probably actually open on the host even if you didn’t allow it through the firewall yourself.
Since UFW and docker are not compatible, I’ve opted to remove UFW completely. Uninstalling UFW does not remove the rules from iptables, but since I never enabled it or made any rules, my iptables is clean. You can wipe your firewall rules clean if you want to start fresh or remove the UFW rules manually.
For most servers I recommend allowing SSH and making the default INPUT and FORWARD iptables policies to DROP, while allowing OUTPUT.
Warning: Script below is destructive. If you have other custom rules, they will go away.
# remove ufw
sudo ufw disable
sudo apt purge ufw -y
sudo apt autoremove -y
# Open the firewall to prevent lock out
sudo iptables -P INPUT ACCEPT
sudo iptables -P FORWARD ACCEPT
sudo iptables -P OUTPUT ACCEPT
# Clear all the things
sudo iptables -F
sudo iptables -t nat -F
sudo iptables -t mangle -F
sudo iptables -X
sudo iptables -Z
# Allow loopback iptables
sudo iptables -A INPUT -i lo -j ACCEPT
sudo iptables -A FORWARD -i lo -j ACCEPT
# Allow Input if established (make iptables stateful)
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
sudo iptables -A INPUT -m conntrack --ctstate INVALID -j DROP
# Allow ssh
sudo iptables -A INPUT -p tcp --dport ssh -j ACCEPT
# Default drop input and forward
sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
# Default allow out
sudo iptables -P OUTPUT ACCEPT
# Make persistent
sudo iptables-save
