Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readLinux
#Linux#Networking#Security#SysAdmin
3D illustration of a firewall wall with layered rule filters catching packets at a network gate

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

bash
# 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'
bash
# 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
bash
# nftables: one file, one atomic transaction cat /etc/nftables.conf
nft
#!/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; } }
bash
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 nftables

Key Comparison Table

Aspectufwiptables (legacy)nftables
AbstractionSimple allow/deny statementsChain and match modulesTables, chains, sets, maps
Rule orderManaged by you with before/after filesAppend/insert manuallyOrder inside the chain
Multiple portsOne rule each, or an app profile-m multiportSets: tcp dport { 22, 80, 443 }
Atomic reloadYes (ufw reload)No (iptables-restore replaces table by table)Yes (single transaction)
PersistenceAutomatic in /etc/ufwManual save + iptables-persistent/etc/nftables.conf
Per-rule countersNo-vcounter statement
NATufw route, /etc/ufw/before.rulesnat tablechain ... hook postrouting
IPv6IPV6=yes in /etc/default/ufwip6tables separatelyOne inet table
Default backend todaynftablesLegacy, or nft shimNative
CommandWhat it prints
ufw status verbosePolicies, logging, active rules
ufw status numberedRule numbers for ufw delete N
iptables -SRules as the commands that created them
iptables -L -n -vHuman-readable with packet counters
nft list rulesetThe whole ruleset, all families
nft -c -f fileParse and validate without applying
ss -tlnpWhat is actually listening, and its process

Practical Edge Cases & Deep Dives

1. Applying a default-deny policy before the SSH rule

bash
# 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 DROP

A 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:

bash
# 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.v4

With 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:

bash
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 order

To 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

bash
$ ufw status | grep 8080 # no rule $ curl -s -o /dev/null -w '%{http_code}\n' http://host:8080 200

Docker 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:

ini
# /etc/docker/daemon.json — publish only on loopback, put a proxy in front { "iptables": true, "ip": "127.0.0.1" }
bash
# 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 DROP

DOCKER-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

nft
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

bash
# 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 -20

A 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

bash
# 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 ACCEPT

iptables -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

SymptomCauseFix
SSH session died after enabling the firewallDefault deny applied before the allow ruleAllow 22 first, or schedule a rollback
App listens but the port is unreachableRule order, wrong interface, or a container published past the firewallCheck counters, ss -tlnp, DOCKER-USER
Rules gone after rebootNo persistenceiptables-save/netfilter-persistent, or nftables.service
iptables and nft show different rulesiptables-nft shim over the same backendPick one interface per host
Duplicate rules after each reloadScript appends without checkingiptables -C, or flush ruleset
Outbound DNS fails with INPUT dropNo established,related ruleAdd conntrack accept before the policy
IPv6 still openIPV6=yes not set, or ip6tables untouchedOne inet table in nftables, or configure both
ufw deny ignored for a subnetBroad allow added earlierufw insert 1 ..., status numbered
Docker container bypasses ufwDocker's nat/FORWARD chains run before INPUT-p 127.0.0.1:..., proxy, or DOCKER-USER
Rate limit blocks legitimate trafficlimit too tight, no burstRaise rate, add burst, exempt known sources
Logs flooded by dropped packetsLOG without limit-m limit --limit 5/min
nft -f refused the fileSyntax error, whole transaction rejectednft -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 tools

Small utilities that fit Linux work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Linux guides

More in Linux

All Linux guides

The guides filed next to this one in Linux, in library order.