If you’re running a modern Linux server, you’ve probably heard that nftables is replacing iptables as the standard firewall framework. After working with both systems across dozens of production servers, I can tell you that the transition to nftables rules offers real benefits: unified IPv4/IPv6 handling, simpler syntax, atomic rule updates, and built-in debugging tools. This guide walks you through setting up nftables rules from scratch, migrating your existing iptables configuration, and applying firewall changes safely without locking yourself out of your server.
Setting up nftables rules to replace iptables on a modern Linux server might feel intimidating at first—the syntax looks different, and the hierarchy of tables, chains, and rules requires a mental shift. But once you understand the structure, nftables actually becomes more intuitive than iptables. You’ll find yourself writing cleaner rulesets that are easier to maintain and debug.
Table of Contents
Why Replace iptables with nftables?
nftables is the modern successor to iptables, developed as part of the Netfilter project to address iptables’ architectural limitations. The Linux kernel has included nftables since version 3.13, and major distributions like Debian, Ubuntu, CentOS, and Fedora now default to nftables for firewall management.
The key advantages of nftables over iptables include unified IPv4 and IPv6 handling—iptables required separate tools (iptables and ip6tables) with duplicate rulesets. With nftables, you write one ruleset that handles both protocols. Additionally, nftables supports atomic rule updates, meaning you can replace an entire ruleset in a single operation without transient connection drops. iptables updates each rule individually, which can cause brief service interruptions.
Built-in tracing makes debugging packet flows significantly easier. Instead of guessing which rule matched a packet, you can trace packets through your ruleset and see exactly what happened. The syntax is also more consistent and flexible—nftables uses a unified syntax for all rule types, while iptables has different syntax patterns for filtering, NAT, and mangling.
Prerequisites and Installing nftables
Before setting up nftables rules, ensure your system meets the basic requirements. You’ll need a Linux kernel version 3.13 or later (most modern distributions meet this), root or sudo access, and a backup of your existing iptables rules if you’re migrating.
Installing nftables on Different Distributions
On Debian and Ubuntu systems, install nftables with: sudo apt update && sudo apt install nftables. For CentOS, RHEL, and Fedora, use: sudo dnf install nftables (or sudo yum install nftables on older systems). On Arch Linux, run: sudo pacman -S nftables.
After installation, check that nftables is working: sudo nft list ruleset. If you see an empty ruleset or no output, nftables is installed correctly. Enable the nftables service to start on boot: sudo systemctl enable nftables.
Understanding nftables Syntax and Structure
nftables organizes firewall rules in a hierarchy: tables contain chains, and chains contain rules. This structure mirrors iptables but with important differences in how you define and reference each component.
Tables: The Top-Level Container
A table in nftables groups related chains and rules together. Tables belong to a protocol family—ip for IPv4, ip6 for IPv6, inet for both, arp for ARP packets, and bridge for bridge device filtering. Most server configurations use the inet family to handle IPv4 and IPv6 in one table.
Create a table with: sudo nft add table inet filter. This creates a table named “filter” in the inet family. You can name tables anything, but “filter” is a common convention for packet filtering rules.
Chains: Where Rules Live
Chains within tables determine when and how rules are evaluated. There are two types: base chains and regular chains. Base chains are entry points from the Netfilter hooks—they specify where in the packet processing pipeline the chain starts. Regular chains are just containers for rules that you can jump to from other chains.
When creating a base chain, you specify the hook (where in the packet processing it attaches), the priority (order of execution when multiple chains exist), and the policy (default action for packets that don’t match any rule).
Rules: Match Conditions and Actions
Each rule in a chain contains match expressions and a verdict (action). When a packet arrives at a chain, nftables evaluates rules in order until one matches. Common verdicts include accept (let the packet through), drop (silently discard), reject (discard and send an error response), and jump (continue processing in another chain).
Rule syntax follows a consistent pattern: nft add rule [family] [table] [chain] [matches] [verdict]. For example, to accept SSH traffic: sudo nft add rule inet filter input tcp dport 22 accept.
iptables vs nftables Command Comparison
One of the quickest ways to learn nftables is comparing commands directly with iptables equivalents. Here are the most common operations you’ll perform, showing both syntaxes side by side.
To list all rules: iptables uses sudo iptables -L, while nftables uses sudo nft list ruleset. To flush all rules: iptables needs sudo iptables -F, and nftables uses sudo nft flush ruleset. For allowing SSH on port 22: iptables would use sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT, while nftables simplifies to sudo nft add rule inet filter input tcp dport 22 accept.
Setting default policies differs significantly. With iptables: sudo iptables -P INPUT DROP. With nftables, you specify the policy when creating the base chain: sudo nft add chain inet filter input { type filter hook input priority 0 ; policy drop ; }.
Notice how nftables uses more natural syntax—”accept” instead of “-j ACCEPT”, “dport 22” instead of “–dport 22”. The command structure reads more like a sentence, which becomes intuitive after working with it for a few days.
Building Your First nftables Ruleset
Let’s build a complete nftables ruleset from scratch. I’ll walk through each step, explaining the logic behind each rule. This example creates a basic firewall for a web server.
Step 1: Create the Table and Base Chains
First, create the main table: sudo nft add table inet firewall. Then create the input chain for incoming traffic: sudo nft add chain inet firewall input { type filter hook input priority 0 ; policy drop ; }. This creates a base chain attached to the input hook with a default drop policy—any packet not explicitly allowed gets blocked.
Create the forward chain for routed traffic: sudo nft add chain inet firewall forward { type filter hook forward priority 0 ; policy drop ; }. And create the output chain for outgoing traffic: sudo nft add chain inet firewall output { type filter hook output priority 0 ; policy accept ; }.
Step 2: Accept Essential Traffic
You need to allow established connections to continue: sudo nft add rule inet firewall input ct state established,related accept. This rule uses connection tracking (conntrack) to recognize packets belonging to existing connections, preventing your current SSH session from being cut off.
Allow loopback traffic: sudo nft add rule inet firewall input iif lo accept. The loopback interface handles local communication, and blocking it can break many services.
Step 3: Open Service Ports
Allow SSH access: sudo nft add rule inet firewall input tcp dport 22 accept. For a web server, open HTTP and HTTPS: sudo nft add rule inet firewall input tcp dport { 80, 443 } accept. The curly braces let you specify multiple ports in one rule.
Allow ICMP for diagnostics: sudo nft add rule inet firewall input ip protocol icmp accept and sudo nft add rule inet firewall input ip6 nexthdr icmpv6 accept. Blocking ICMP entirely makes troubleshooting network issues extremely difficult.
Step 4: Verify Your Ruleset
Check what you’ve created: sudo nft list ruleset. You should see your table with chains and rules listed. The output shows the complete ruleset in nftables’ native format, which you can save to a file for persistence.
Common Firewall Rules for SSH, HTTP, and HTTPS
Production servers typically need more refined rules than basic port openings. Here are practical rules for common scenarios that go beyond the basics.
Rate Limiting SSH Connections
SSH brute force attacks remain common. Use nftables metering to limit connection attempts: sudo nft add rule inet firewall input tcp dport 22 ct state new meter ssh_meter { ip saddr timeout 5m limit rate 3/minute } accept. This allows only three new SSH connections per minute from each IP address. Attackers quickly hit the limit while legitimate users rarely notice.
Handling Web Traffic with Connection Limits
For busy web servers, you might limit concurrent connections: sudo nft add rule inet firewall input tcp dport { 80, 443 } ct state new meter web_meter { ip saddr timeout 1h limit rate over 100/second } drop. This drops connections from IPs exceeding 100 requests per second while allowing normal traffic.
Logging Dropped Packets
For debugging, log packets before dropping them: sudo nft add rule inet firewall input log prefix "DROPPED: " flags all counter drop. The log prefix helps you identify dropped packets in system logs, and counter tracks how many packets matched this rule.
Remember to place this logging rule at the end of your input chain. It acts as a catch-all for packets that didn’t match any accept rule. Without it, drops are silent and troubleshooting becomes much harder.
Applying Firewall Rules Safely Without Locking Yourself Out
The biggest fear when configuring firewalls remotely is locking yourself out. I’ve seen it happen to experienced administrators. Here’s how to apply rules safely.
The Cron Safety Net Method
Before applying new rules, create a cron job that flushes the firewall after 5 minutes. Add this line to root’s crontab: */5 * * * * /usr/sbin/nft flush ruleset && /usr/sbin/nft -f /etc/nftables.conf. This ensures that even if you lock yourself out, the firewall resets to a known-good state within 5 minutes.
Apply your new rules, verify you still have access, and then remove the cron job. Only disable the safety net after confirming everything works.
The at Command Method
Alternatively, use the at command to schedule a one-time reset. Run: echo "nft flush ruleset && nft -f /etc/nftables.conf" | at now + 5 minutes. If you get locked out, the scheduled job runs and restores your original rules. Cancel it with atrm after confirming the new rules work.
SSH Key-Based Persistent Sessions
When making firewall changes, use an SSH connection with ServerAliveInterval set to keep the session active. Add to your SSH config: Host myservern ServerAliveInterval 60n ServerAliveCountMax 3. This prevents your connection from timing out during rule changes.
The conntrack rule accepting established connections is critical here. Always add this rule first: sudo nft add rule inet firewall input ct state established,related accept. This ensures your current SSH session stays connected even when you flush and reload rules.
Migrating from iptables to nftables
If you have existing iptables rules, you don’t need to rewrite them from scratch. The iptables-translate tool converts iptables commands to nftables equivalents automatically.
Using iptables-translate
For single commands, pass the iptables syntax to iptables-translate: sudo iptables-translate -A INPUT -p tcp --dport 22 -j ACCEPT. Output shows: nft add rule ip filter INPUT tcp dport 22 accept. The tool handles the syntax conversion for you.
For entire rulesets, use iptables-save and pipe through iptables-restore-translate: sudo iptables-save | sudo iptables-restore-translate > ruleset.nft. This generates a complete nftables ruleset file from your current iptables configuration.
Manual Migration Steps
Start by exporting your current iptables rules: sudo iptables-save > iptables-rules.txt. Keep this file as a backup. Then translate the rules: sudo iptables-restore-translate -f iptables-rules.txt > nftables-rules.conf.
Review the generated nftables configuration. You’ll likely want to make adjustments—combining rules that can share expressions, adding connection tracking where appropriate, and ensuring the ruleset follows nftables best practices.
Testing Your Migrated Ruleset
Before committing to the migration, test in a staging environment or VM first. Load the translated ruleset: sudo nft -f nftables-rules.conf. Verify all services still work as expected, then save the ruleset: sudo nft list ruleset > /etc/nftables.conf.
On production systems, schedule a maintenance window for the migration. Even with careful testing, having a rollback plan is essential. Keep your iptables rules file accessible so you can revert if unexpected issues arise.
Saving and Loading Rules Automatically on Boot
Firewall rules only exist in memory by default. After a reboot, you need to reload them. Different distributions handle this differently, but the core approach remains similar.
Debian and Ubuntu
On Debian-based systems, the nftables package includes a systemd service. Save your current ruleset: sudo nft list ruleset | sudo tee /etc/nftables.conf. The service reads this file on boot. Enable it: sudo systemctl enable nftables.
To reload rules after changes: sudo systemctl reload nftables. This applies the ruleset without restarting the service, maintaining established connections.
RHEL and CentOS
Red Hat systems use a similar approach but with different file locations. Save rules to /etc/sysconfig/nftables.conf: sudo nft list ruleset | sudo tee /etc/sysconfig/nftables.conf. Enable the service: sudo systemctl enable nftables.
Manual Loading Script
For custom configurations, create a boot script. Save your ruleset to /etc/nftables.conf, then create /etc/rc.local with: #!/bin/bashn/usr/sbin/nft -f /etc/nftables.conf. Make it executable: sudo chmod +x /etc/rc.local.
Some distributions use different init systems. Check your distribution’s documentation for the preferred persistence method. The key principle remains: save the ruleset in nftables format to a file and load it at boot.
Advanced nftables Features: Rate Limiting and Tracing
Beyond basic filtering, nftables includes powerful features that iptables lacks or makes difficult. Understanding these capabilities helps you build more sophisticated firewall policies.
Rate Limiting with Meters
nftables meters track packet rates per IP address or other criteria. We used meters earlier for SSH rate limiting, but they apply to many scenarios. Limit DNS query rates to prevent amplification attacks: sudo nft add rule inet firewall input udp dport 53 meter dns_meter { ip saddr timeout 1m limit rate 10/second } accept.
Meters are more flexible than iptables’ recent module. You can meter on any expression, not just source IP. Meter on destination port, protocol, or combinations for fine-grained control.
Packet Tracing for Debugging
When rules don’t behave as expected, nftables tracing reveals exactly what happens to each packet. Enable tracing on a specific rule: sudo nft add rule inet firewall input tcp dport 22 meta nftrace set 1. Then monitor the trace: sudo nft monitor trace.
You’ll see detailed output showing each rule the packet matched, the final verdict, and why. This visibility makes debugging rulesets significantly faster than adding log statements everywhere.
Remove tracing rules after debugging. They add overhead to packet processing and can fill logs quickly on busy servers. Use them as a diagnostic tool, not a permanent feature.
Frequently Asked Questions
Which is better, nftables or iptables?
nftables is better for modern Linux systems. It offers unified IPv4/IPv6 handling, atomic rule updates, built-in tracing, and more consistent syntax. iptables remains functional but is considered legacy software. For new deployments, use nftables.
What is the difference between nftables and iptables?
nftables and iptables differ in architecture and syntax. nftables uses a unified framework for all packet types, while iptables requires separate tools for IPv4, IPv6, ARP, and bridging. nftables supports atomic ruleset replacement, built-in tracing, and more flexible expression matching. The syntax is more consistent, though it requires learning new patterns.
Is iptables replaced by nftables?
Yes, iptables is replaced by nftables as the preferred Linux firewall framework. The Netfilter project developed nftables as iptables’ successor. Modern distributions default to nftables, and the iptables command now often wraps nftables internally using compatibility layers. However, iptables remains available for legacy systems and transitional use.
Is nftables compatible with iptables?
nftables and iptables can coexist on the same system but cannot manage the same rules. The iptables-translate tool converts iptables syntax to nftables. The iptables-nft compatibility layer lets you use iptables commands that internally create nftables rules. However, you should choose one system for your firewall management to avoid conflicts.
How do I avoid SSH lockout when applying nftables rules remotely?
To avoid SSH lockout, first add a conntrack rule to accept established connections: ‘nft add rule inet filter input ct state established,related accept’. Use a safety net like a cron job or at command that resets the firewall after 5 minutes. Apply your changes, verify SSH access still works, then remove the safety net. Always test new rulesets in a staging environment before production deployment.
Conclusion
Replacing iptables with nftables rules on your Linux server requires learning new syntax and concepts, but the benefits are substantial. You get unified IPv4 and IPv6 handling, atomic rule updates that don’t drop connections, built-in tracing for debugging, and a more consistent syntax that becomes intuitive over time.
Start with the basic ruleset structure—create tables, define base chains with appropriate hooks, and add rules for your essential services. Always include conntrack rules to preserve established connections, especially when working remotely. Use the safety net techniques I described to prevent lockouts during rule changes.
The iptables-translate tool simplifies migration from existing iptables rulesets. Convert your rules, review the output, and test thoroughly before deploying to production. Once your nftables ruleset is stable, configure automatic loading on boot appropriate for your distribution.
nftables represents the future of Linux firewalling. Learning it now prepares you for modern system administration and gives you powerful tools that iptables lacks. Take the time to understand the table-chain-rule hierarchy, practice building rulesets in a test environment, and soon you’ll find nftables rules become second nature.