Linux Firewall Rules: ufw, nftables and iptables

A firewall that denies inbound traffic by default shrinks a server's exposure to the few ports you chose to open. The same firewall is also the most common way to lose access to your own machine, so the order you apply it in matters as much as the rules.

Allow SSH before you enable anything

With ufw, add the SSH rule first and only then run ufw enable, because enabling a default-deny firewall with no SSH rule cuts the connection you are typing over. nftables and iptables-restore load a whole ruleset in one step, so SSH just has to be in the file. Whichever you use, keep your current session open and confirm a fresh login in a second terminal before closing it.

ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp
ufw allow 443/tcp
ufw enable

Limit a service to one network

Databases and caches rarely need to be reachable from everywhere. Naming a source restricts a port to that address or range, so PostgreSQL can be open to your private network and invisible to the internet. Never leave 3306, 5432, 6379, 27017 or 9200 open to everyone.

ufw allow from 10.0.0.0/8 to any port 5432 proto tcp

Docker bypasses ufw

Docker publishes ports by inserting its own iptables rules ahead of the chains ufw manages, so a container published as 8080:8080 is reachable even though ufw denies 8080. Publish on 127.0.0.1 and put a reverse proxy in front, or filter in the DOCKER-USER chain.

Keep ICMPv6 working

Unlike IPv4, IPv6 needs ICMP to function: neighbour discovery is how a host finds its router and its neighbours. A firewall that drops all ICMPv6 silently breaks IPv6 connectivity. Allow the neighbour and router discovery types and the error messages, and decide separately whether to answer ping.

meta l4proto ipv6-icmp icmpv6 type { destination-unreachable, packet-too-big,
  time-exceeded, parameter-problem, nd-router-solicit, nd-router-advert,
  nd-neighbor-solicit, nd-neighbor-advert } accept

Open the Firewall rules generator

Frequently asked questions

Should I use ufw, nftables or iptables?

ufw is the simplest on Ubuntu and Debian. nftables is the modern kernel framework that replaces iptables, and iptables is still everywhere. On current distributions the iptables command often runs on top of nftables anyway.

How do I test a firewall change safely?

Keep your existing SSH session open, apply the change, and open a second connection to confirm it works. For nftables you can also check syntax first with nft -c -f, and schedule a command to remove the table after a minute in case you are locked out.

Does blocking ping make a server more secure?

Not meaningfully. Scanners find hosts by other means, and blocking ICMP echo mainly makes troubleshooting harder. Closing unneeded ports is what reduces exposure.

Guides