Linux Firewalls: ufw, iptables, and nftables Rules and Persistence
First-match ordering, stateful filtering, and persistence: the three ideas behind every Linux firewall. Plus why Docker-published ports ignore ufw and how DOCKER-USER closes them.

Quick Summary
Linux firewalling is netfilter: hooks in the network stack that a rule set inspects packet by packet. iptables was its first widely used interface, nftables is its replacement (in-kernel since 3.13, the default on Debian 10+, RHEL 8+, and Ubuntu 20.04+), and ufw and firewalld are front ends that generate one of the two. On modern systems iptables usually still exists as iptables-nft, a translation shim over nftables, so mixing iptables and nft commands on one host produces two views of the same ruleset and a great deal of confusion.
Three ideas do most of the work. Rules are evaluated in order and the first matching terminating target wins, so a DROP above an ACCEPT decides the packet. Stateful filtering means you accept the reply traffic of connections you allowed (ct state established,related accept), rather than opening return ports by hand. And persistence is separate from the live ruleset: ufw and firewalld persist by themselves, while raw iptables/nft rules vanish on reboot unless you save them.
The operational risk is the same everywhere: a default-deny policy applied before the SSH allow rule ends an administrator's session, and a container runtime that writes its own chains can bypass the rules you wrote. This guide covers ufw rule syntax and ordering, iptables chain and persistence semantics, nftables syntax with sets and atomic reload, and the interactions that explain "the port is closed but the app is listening".
Basic Syntax & Core Signatures
# ufw: default policies, then explicit allows, then enable
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp
ufw allow from 10.0.0.0/8 to any port 5432 proto tcp
ufw allow in on eth0 to any port 443
ufw limit ssh # 6 connections/minute per source, brute-force damping
ufw route allow in on eth0 out on eth1 to 172.16.0.0/12 port 80 # forwarding
ufw enable # prompts about disrupting SSH
ufw status verbose numbered # numbered is what you pass to delete
ufw delete 3
ufw --dry-run status numbered # rule numbers without applying
ufw app list && ufw allow 'Nginx Full'# iptables: filter table, built-in chains, first match wins
iptables -L -n -v --line-numbers
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -j DROP
iptables -P INPUT DROP # policy applies only when no rule matched
# Insert instead of append (top of chain)
iptables -I INPUT 1 -s 203.0.113.7 -j DROP
# Log before dropping, rate-limited
iptables -A INPUT -m limit --limit 5/min -j LOG --log-prefix 'ipt-deny: ' --log-level 4
# Persist and restore
iptables-save > /etc/iptables/rules.v4
iptables-restore < /etc/iptables/rules.v4
netfilter-persistent save # with iptables-persistent installed# nftables: one file, one atomic transaction
cat /etc/nftables.conf#!/usr/sbin/nft -f
flush ruleset
table inet filter {
set admin_nets { type ipv4_addr; flags interval; elements = { 10.0.0.0/8, 203.0.113.0/24 } }
chain input {
type filter hook input priority filter; policy drop;
ct state established,related accept
iif "lo" accept
ip protocol icmp accept
ip6 nexthdr icmpv6 accept
tcp dport { 22, 80, 443 } accept
ip saddr @admin_nets tcp dport 5432 accept
tcp dport 22 limit rate 6/minute burst 10 packets accept
counter comment "dropped input" drop
}
chain forward { type filter hook forward priority filter; policy drop; }
chain output { type filter hook output priority filter; policy accept; }
}nft -f /etc/nftables.conf # atomic: applies all or nothing
nft list ruleset
nft list table inet filter
nft -c -f /etc/nftables.conf # syntax check only
systemctl enable --now nftablesKey Comparison Table
| Aspect | ufw | iptables (legacy) | nftables |
|---|---|---|---|
| Abstraction | Simple allow/deny statements | Chain and match modules | Tables, chains, sets, maps |
| Rule order | Managed by you with before/after files | Append/insert manually | Order inside the chain |
| Multiple ports | One rule each, or an app profile | -m multiport | Sets: tcp dport { 22, 80, 443 } |
| Atomic reload | Yes (ufw reload) | No (iptables-restore replaces table by table) | Yes (single transaction) |
| Persistence | Automatic in /etc/ufw | Manual save + iptables-persistent | /etc/nftables.conf |
| Per-rule counters | No | -v | counter statement |
| NAT | ufw route, /etc/ufw/before.rules | nat table | chain ... hook postrouting |
| IPv6 | IPV6=yes in /etc/default/ufw | ip6tables separately | One inet table |
| Default backend today | nftables | Legacy, or nft shim | Native |
| Command | What it prints |
|---|---|
ufw status verbose | Policies, logging, active rules |
ufw status numbered | Rule numbers for ufw delete N |
iptables -S | Rules as the commands that created them |
iptables -L -n -v | Human-readable with packet counters |
nft list ruleset | The whole ruleset, all families |
nft -c -f file | Parse and validate without applying |
ss -tlnp | What is actually listening, and its process |
Practical Edge Cases & Deep Dives
1. Applying a default-deny policy before the SSH rule
# Wrong order on a remote host: the session dies immediately
iptables -P INPUT DROP
# Right: allow the session's own traffic first, then the policy
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -j ACCEPT
iptables -P INPUT DROPA policy change does not break established connections; the next new packet without an allow rule does. The safe procedure is a scheduled rollback that is cancelled only after you confirm access:
# revert in 5 minutes unless cancelled
( sleep 300; iptables-restore < /root/rules.backup ) &
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -P INPUT DROP
# after confirming a new SSH session works:
kill %1
iptables-save > /etc/iptables/rules.v4With ufw, ufw enable asks about disrupting SSH and ufw allow 22/tcp before enabling is the same guard; ufw --dry-run prints the resulting iptables commands so you can see the order the front end chose.
2. ufw rule order and the before/after hooks
ufw inserts rules in the order you add them to its chain, and evaluates top-down, so a broad allow added first shadows a later deny:
ufw allow from 10.0.0.0/8 # added first
ufw deny from 10.0.0.7 # never reached for that host
ufw status numbered # shows the actual orderTo interpose rules before ufw's own, use /etc/ufw/before.rules (*filter section, evaluated first) or ufw insert 1 deny from 10.0.0.7, then ufw reload. Forwarded traffic (docker run -p included) is governed by ufw route, not by plain ufw allow, which is the root of the next case.
3. Docker publishes ports past ufw
$ ufw status | grep 8080 # no rule
$ curl -s -o /dev/null -w '%{http_code}\n' http://host:8080
200Docker inserts rules into the nat table's DOCKER chain and the FORWARD chain, and its DNAT happens before ufw's INPUT rules ever see the packet. Since Docker's rules are appended after the filter chain's policy, an ufw default deny incoming does not close the published port. The available fixes, each with a cost:
# /etc/docker/daemon.json — publish only on loopback, put a proxy in front
{ "iptables": true, "ip": "127.0.0.1" }# Bind the published port to a specific address
docker run -p 127.0.0.1:8080:8080 app
# Or filter the DOCKER-USER chain, which is evaluated before Docker's own rules
iptables -I DOCKER-USER -i eth0 ! -s 10.0.0.0/8 -j DROPDOCKER-USER is the supported hook; adding rules to INPUT after Docker has already accepted the translated packet has no effect.
4. Stateful filtering, and why --dport 22 alone is enough
chain input {
type filter hook input priority filter; policy drop;
ct state established,related accept # replies to your outbound traffic
ct state invalid drop
tcp dport 22 accept
}Without the established,related line, an outbound SSH connection or a DNS reply is dropped by the default policy, because the rule set only describes the first packet. related additionally covers ICMP errors and FTP-style helpers. Conversely, permitting ct state new on a wide port range is the usual cause of an accidentally exposed database: the rule you wrote for the web tier applies to the whole internet.
5. Verifying a rule actually permits the packet
# Is anything listening, and on which address?
ss -tlnp | grep -E ':(22|80|443|5432)\b'
# Counters: send traffic, then compare
iptables -L INPUT -n -v --line-numbers
nft list chain inet filter input
# From outside the host
nc -zv host 443 ; curl -sv --max-time 3 https://host/ 2>&1 | head -20A packet counted at a DROP rule and absent from the allow rule means ordering or a match condition (interface, source, protocol) is wrong. A packet that never appears in any counter was dropped before netfilter — by a security group, a cloud provider's network ACL, or the host's own routing — or never reached the host at all. nft counters and iptables -v packet counts are the difference between guessing and knowing which rule saw the packet.
6. Rules that vanish on reboot, and rules duplicated on reload
# iptables without persistence: gone after reboot
iptables-save > /etc/iptables/rules.v4
apt install iptables-persistent && netfilter-persistent save
# nftables with the service enabled: flushed and reloaded at boot
systemctl enable --now nftables
# A reload script that appends instead of replacing duplicates every run
iptables -A INPUT -p tcp --dport 443 -j ACCEPT # run twice -> two rules
iptables -C INPUT -p tcp --dport 443 -j ACCEPT || iptables -A INPUT -p tcp --dport 443 -j ACCEPTiptables -C checks for an exact rule before adding it, which makes provisioning idempotent. With nftables the equivalent is a flush ruleset at the top of the file, since nft -f applies the whole file as one transaction.
Common Runtime & Configuration Mistakes
| Symptom | Cause | Fix |
|---|---|---|
| SSH session died after enabling the firewall | Default deny applied before the allow rule | Allow 22 first, or schedule a rollback |
| App listens but the port is unreachable | Rule order, wrong interface, or a container published past the firewall | Check counters, ss -tlnp, DOCKER-USER |
| Rules gone after reboot | No persistence | iptables-save/netfilter-persistent, or nftables.service |
iptables and nft show different rules | iptables-nft shim over the same backend | Pick one interface per host |
| Duplicate rules after each reload | Script appends without checking | iptables -C, or flush ruleset |
| Outbound DNS fails with INPUT drop | No established,related rule | Add conntrack accept before the policy |
| IPv6 still open | IPV6=yes not set, or ip6tables untouched | One inet table in nftables, or configure both |
ufw deny ignored for a subnet | Broad allow added earlier | ufw insert 1 ..., status numbered |
| Docker container bypasses ufw | Docker's nat/FORWARD chains run before INPUT | -p 127.0.0.1:..., proxy, or DOCKER-USER |
| Rate limit blocks legitimate traffic | limit too tight, no burst | Raise rate, add burst, exempt known sources |
| Logs flooded by dropped packets | LOG without limit | -m limit --limit 5/min |
nft -f refused the file | Syntax error, whole transaction rejected | nft -c -f file first |
A firewall is the one system where a correct rule set and an unreachable service look identical from outside. The workable routine is to read the live ruleset rather than the intended one (nft list ruleset, iptables -S, ufw status numbered), confirm which process is listening and on which address, test from a machine that is genuinely outside, and only then change a rule — with the default policy, the state rule, and persistence each verified separately.
Try matching browser tools
All toolsSmall utilities that fit Linux work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Linux guides
All Linux guidesBash Indexed Arrays, Associative Maps, and Parameter Expansion
Quoting decides whether an array stays a list, and the expansion operators replace most external text tools. Includes set -u, mapfile, namerefs, and the bash 3.2 differences that break scripts on macOS.
Parsing JSON and YAML in Shell Pipelines with jq and yq
jq is a filter language, not a pretty-printer. The operators that do the work, --arg versus string interpolation, in-place YAML edits, and how to tell which yq is installed before writing a command.
Linux Memory, Swap, the OOM Killer, vmstat, and sysctl Tuning
MemAvailable versus used, the vmstat columns that prove thrashing, how the OOM killer picks its victim, and the sysctl keys that belong in /etc/sysctl.d instead of a one-off command.
Linux Users, Groups, sudoers, and PAM Access Control
The four account files, the sudoers grammar with aliases and drop-ins, and the PAM stack where logins actually succeed or fail. Includes the flags that lock an account without disabling SSH keys.
More in Linux
All Linux guidesThe guides filed next to this one in Linux, in library order.