Linux firewall examples with nftables and iptables
More actions
Practical Linux firewall examples for modern nftables systems and for environments that still expose the iptables command syntax.
nftables and iptables today
The Netfilter project describes the older xtables/legacy framework as legacy and provides migration tools for moving rules to nftables.
Some Linux distributions still provide the familiar iptables command while using the nftables kernel backend. Do not assume that seeing an iptables binary means the system is using the legacy x_tables backend.
Check the installed tools and active ruleset before making changes.
iptables --version nft list ruleset
Back up the current rules
If an iptables-compatible ruleset exists:
iptables-save > iptables-backup.txt
For nftables:
nft list ruleset > nftables-backup.nft
Store the backup somewhere that remains accessible if network connectivity is lost.
Translate an iptables rule
The Netfilter project provides iptables-translate to show the nftables equivalent of an iptables command.
iptables-translate -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -j ACCEPT
This is useful when rationalising old scripts before creating the final nftables ruleset.
Example nftables test table
The following example creates a separate demonstration table and keeps the input policy at accept, which avoids silently turning a documentation example into a complete host firewall.
nft add table inet twdemo
nft 'add chain inet twdemo input { type filter hook input priority 10; policy accept; }'
nft add rule inet twdemo input ct state established,related accept
nft add rule inet twdemo input ip saddr 192.0.2.0/24 tcp dport 22 acceptInspect the result:
nft list table inet twdemo
Remove it when finished:
nft delete table inet twdemo
Legacy iptables syntax examples
For systems intentionally using iptables-compatible syntax, use conntrack state matching rather than copying very old -m state examples.
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT iptables -A INPUT -p tcp -s 192.0.2.0/24 --dport 22 -m conntrack --ctstate NEW -j ACCEPT
iptables -A INPUT -s 198.51.100.25 -j DROP
These examples are individual rules, not a complete firewall policy.
Migrating a complete ruleset
The Netfilter migration tooling can translate an exported iptables ruleset:
iptables-restore-translate -f iptables-backup.txt > ruleset.nft
Review the translated file carefully before loading it.