Guides · Hardening · updated 3 Dec 2026
Docker ignores UFW: how to stop published container ports being open to the internet
Docker writes its own iptables rules ahead of UFW, so ufw deny 5432 does not protect a container published with -p 5432:5432. A database exposed this way is one of the most common ways servers get compromised.
See what is published and to whom
0.0.0.0 or [::] means every interface, including the internet.
docker ps --format '{{.Names}}\t{{.Ports}}' sudo ss -ltnp | grep -E ':(5432|3306|6379|27017)\b'Best fix: publish on localhost only
The container is then reachable by programs on the same machine (your web server or app) and by nobody else.
docker run -p 127.0.0.1:5432:5432 ... # docker compose: # ports: # - "127.0.0.1:5432:5432"Other containers that must stay public: use the DOCKER-USER chain
Docker leaves this chain for you and evaluates it before its own rules. This drops new connections from the internet to containers; add ACCEPT rules above it for the ports you want public. Replace eth0 with your public interface (ip route get 1.1.1.1).
sudo iptables -I DOCKER-USER -i eth0 -m conntrack --ctstate NEW -j DROP sudo iptables -I DOCKER-USER -i eth0 -p tcp --dport 443 -m conntrack --ctstate NEW -j ACCEPT # example: keep one port publicMake it survive a reboot
Rules added by hand are lost at reboot. Put them in a systemd unit that runs after docker.service, or in your firewall tool's persistent configuration.
Verify from outside
From a different machine, scan your own server only.
nmap -Pn -p 5432,3306,6379 SERVER_IP # filtered or closed
Common mistakes
- Using -p 5432:5432 in a compose file copied from a tutorial.
- Assuming ufw status shows the real exposure: it does not show Docker's rules.
- Dropping new connections in DOCKER-USER without allowing the ports your sites use.
How to undo it
Remove the rule with sudo iptables -D DOCKER-USER <same rule>, or recreate the container with the old port mapping.
Sources
Commands are for Debian and Ubuntu unless noted. Test on a copy first and keep a backup: you are responsible for changes on your own systems.