UFW vs iptables vs nftables: Which Linux Firewall Should You Use?

Comparison graphic of UFW, iptables and nftables commands in front of a firewall shield.

Fail2ban — which we set up in the previous post to stop brute-force attacks — reacts to abuse: it watches your logs, notices repeated failures, and bans the source. A firewall works differently: it doesn’t wait for bad behavior, it enforces policy from the start. If a port isn’t explicitly allowed, connections to it are blocked before any service gets a chance to respond — there’s no login attempt to fail, no request to log, because the traffic never reaches anything in the first place.

Together, they cover the two layers that matter most for an internet-facing server. Fail2ban handles the “someone’s actively attacking me” case. Your firewall handles the “this port should never have been reachable in the first place” case.

This guide compares the three tools you’ll run into on a Linux server — UFW, iptables, and nftables — explains where each one fits, and shows the same basic ruleset written in all three so you can see exactly how they differ.

Scope note: This guide uses commands for Debian-based distributions (Debian, Ubuntu, and derivatives), consistent with the rest of this series. The concepts apply everywhere, but package names and defaults shift slightly on RHEL-based distros.

What a firewall actually does

At its core, a firewall inspects packets as they arrive at (or leave) your server and decides, based on rules you define, whether to allow, drop, or reject them. Rules are typically matched on port, protocol, and source/destination address.

DROP vs. REJECT

Every rule that blocks traffic has to pick one of two behaviors, and it’s worth understanding the difference before you write your first rule:

For an internet-facing server, a default-deny policy is generally a sensible baseline. Whether unmatched traffic should be dropped or rejected depends on the environment: DROP avoids sending an explicit response, while REJECT can provide faster and clearer failures for legitimate clients.

The three tools in this guide aren’t three competing implementations of the same thing — they sit at different layers:

That distinction matters: you’re not really choosing between three equivalent options. You’re choosing how much you want to work with the engine directly versus through a simplified interface.

UFW (Uncomplicated Firewall)

Who it’s for: beginners, simple servers, anyone who wants sane defaults without memorizing chain syntax (a “chain” is an ordered list of rules a packet is checked against, top to bottom, until one matches — more on this in the iptables section below).

UFW trades flexibility for approachability. Many single-server setups — a VPS running a blog, an API, or a handful of services — don’t need anything more granular than “allow these ports, deny everything else.”

Install

sudo apt install ufw

Set a sane default posture before opening anything

sudo ufw default deny incoming
sudo ufw default allow outgoing

Allow the ports you actually need

sudo ufw allow 2222/tcp # SSH, replace with your actual port
sudo ufw allow 80/tcp # HTTP
sudo ufw allow 443/tcp # HTTPS

Enable

sudo ufw enable

Check what’s active

sudo ufw status verbose

Removing a rule

The simplest way is to repeat the same allow/deny line with delete in front of it:

sudo ufw delete allow 2222/tcp

If you don’t remember the exact syntax a rule was added with, list rules with numbers instead and delete by number:

sudo ufw status numbered
sudo ufw delete 3 # deletes whichever rule is listed as #3

Persistence

Unlike iptables or nftables, there’s no separate save step. Every ufw allow/deny/delete command writes straight to files under /etc/ufw/ (rules live in user.rules for IPv4 and user6.rules for IPv6), and UFW is enabled at boot and automatically reapplies those rules. As soon as a command returns successfully, it’s already durable.

Pros: readable syntax, simpler to configure safely, fast to set up.

Cons: limited for complex rule logic — NAT, per-source conditions, sets, or custom rate limits beyond ufw limit quickly become awkward. Once your ruleset outgrows “allow/deny by port,” you’ll feel the ceiling.

iptables

Who it’s for: legacy systems, servers where existing rules already depend on it, or situations that call for very fine-grained control and you’re already fluent in its syntax.

iptables organizes rules into chains — INPUT (incoming traffic), OUTPUT (outgoing traffic), and FORWARD (traffic passing through, relevant for routers/NAT) — grouped into tables (filter, nat, mangle, etc.). Rules are evaluated top to bottom, and order matters: when a rule matches, its actions are applied, and a terminating verdict such as ACCEPT, DROP, or REJECT can end processing of that chain.

A basic ruleset

Allow loopback traffic, established/related connections, SSH, HTTP, HTTPS, drop everything else:

# Allow traffic that's part of a connection already in progress
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
# Allow incoming SSH on the custom port
sudo iptables -A INPUT -p tcp --dport 2222 -j ACCEPT
# Allow incoming HTTP
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
# Allow incoming HTTPS
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
# Allow local/loopback traffic (needed by many services talking to themselves)
sudo iptables -A INPUT -i lo -j ACCEPT
# Set the default policy for anything not accepted above
sudo iptables -P INPUT DROP

Notice that first rule: UFW handles established/related traffic for you automatically; with iptables, you need to add it yourself. Without it, replies to connections initiated by the server can be dropped when they reach the INPUT chain. Putting it near the top lets established traffic be accepted before later rules are evaluated.

Note: -m state --state is the older state-matching syntax. For new rules, -m conntrack --ctstate is the preferred syntax, which provides the same basic connection-state matching plus additional conntrack features.

Persistence

Rules like this don’t survive a reboot on their own — you need to persist them.

sudo apt install iptables-persistent
sudo netfilter-persistent save

Removing a rule

The easiest way is to swap -A (append) for -D (delete) and repeat the exact rule you want gone:

sudo iptables -D INPUT -p tcp --dport 80 -j ACCEPT

That only works if you can reproduce the rule’s exact syntax, though — for anything more complex, it’s usually faster to list rules with line numbers and delete by position instead:

sudo iptables -L INPUT --line-numbers -v
sudo iptables -D INPUT 3 # deletes rule #3 in the INPUT chain

Deleting by number is convenient, but note that once you remove a rule, every rule below it shifts up one position — re-run --line-numbers before deleting a second rule rather than trusting the numbers from before. And as with adding rules, don’t forget to netfilter-persistent save afterward, or the deleted rule will come back on reboot.

Pros: extremely well documented (decades of tutorials and Stack Overflow answers), precise control over every stage of packet handling.

Cons: syntax is unforgiving — a misplaced rule or wrong order can silently defeat the ruleset. It’s also the older interface: newer distributions increasingly use nftables as the underlying firewall framework, so new deployments are generally better served by learning nftables directly.

One more gap worth knowing about: ip6tables. Everything above only filters IPv4. iptables has a near-identical sibling, ip6tables, that handles IPv6 traffic — and it needs its own separate ruleset, written on its own (iptables-persistent saves both the IPv4 and IPv6 rulesets, so the save step is shared). It’s easy to lock a server down with iptables, feel done, and not realize IPv6 traffic to the same ports is sailing through completely unfiltered because it was never touched. If the server has IPv6 enabled, ip6tables needs the same INPUT/OUTPUT/FORWARD treatment as its IPv4 counterpart — this is exactly the kind of split nftables was built to eliminate, as covered next. And remember to allow ICMPv6 (see the nftables note below).

Important: iptables can use the nftables backend. On modern distributions, the iptables command may be provided by iptables-nft, which translates iptables-style rules to the nftables backend. So “using the iptables command” and “using the old iptables kernel backend” are not necessarily the same thing.

nftables

Who it’s for: anyone setting up a firewall from scratch on a modern distro. This is the modern Linux packet-filtering framework, and it’s increasingly the underlying firewall technology on modern distributions even if you’re only ever touching UFW.

nftables was built to fix iptables’ rough edges: one syntax for both IPv4 and IPv6 instead of separate iptables/ip6tables commands, and a cleaner, more readable rule structure.

A note on tables: in iptables, tables (filter, nat, mangle) already exist — you just reference them. UFW abstracts them away entirely. nftables works differently: tables aren’t pre-created. The table inet filter { ... } block in the config below is what creates it, and chains can only exist inside a table.

Install and configure

Install nftables if needed:

sudo apt install nftables

Then open /etc/nftables.conf:

sudo nano /etc/nftables.conf

In the file, if it’s the default one, keep the first two lines (the shebang and flush ruleset) and replace the table inet filter block with:

/etc/nftables.conf
table inet filter {
chain input {
type filter hook input priority 0;
policy drop;
ct state established,related accept
iif lo accept
tcp dport 2222 accept # SSH: replace with your port
tcp dport { 80, 443 } accept
}
}

Note: If this is a dedicated nftables configuration and no other software manages nftables rules on the server, you can keep the default flush ruleset line. If Docker, Fail2ban, or another tool manages its own nftables tables, remove flush ruleset and make sure your configuration does not overwrite or flush those tables.

Important: This is a minimal teaching example, not a complete production firewall. A real server should also account for ICMP/ICMPv6, invalid connection states, DNS/NTP requirements where applicable, and any other services or traffic the host needs.

Then check the configuration without applying it. If there are no errors, load it as a transaction:

sudo nft -c -f /etc/nftables.conf
sudo nft -f /etc/nftables.conf

Advanced: how multiple nftables chains interact

A note on priority and multiple chains: the priority 0 in the chain definition above controls something that doesn’t come up in iptables, where each hook (INPUT, OUTPUT, FORWARD) only ever has one chain. In nftables, you can attach multiple base chains to the same hook, and priority decides the order they run in — lower numbers run first.

This matters because of how verdicts interact across chains: drop is immediate and final — the moment any chain drops a packet, it’s discarded, full stop, no matter what other chains exist. Accept is not final — it only means “not blocked by this chain.” The packet still has to pass through every other chain on that same hook, in priority order, before it’s genuinely let through. So it’s possible for a packet to be accepted by an early (lower-priority-number) chain and then dropped later by a chain with a higher priority number on the same hook.

For example, this ruleset defines two base chains on the same input hook:

Warning: the second chain drops all incoming traffic that isn’t accepted by a rule in it, including your SSH session. Run this demo from a VM console, never over SSH on a server you care about.

sudo nft add table inet demo
sudo nft add chain inet demo first { type filter hook input priority 0 \; policy accept \; }
sudo nft add rule inet demo first tcp dport 8080 accept
sudo nft add chain inet demo second { type filter hook input priority 1 \; policy drop \; }
# clean up afterwards: sudo nft delete table inet demo

A TCP packet on port 8080 hits the first chain (priority 0) and gets accepted there. But that’s not the end of the story — the packet then continues on to the second chain (priority 1), which has no rules of its own and a default policy of drop. Since nothing in that chain matches the packet, its policy applies, and the packet is dropped anyway — despite being accepted a moment earlier. The earlier accept never actually let the packet through; it only cleared that one chain.

For a single-base-chain setup like the main ruleset earlier, none of this is a concern — there’s only one base input chain on that hook, so the accept and drop behavior is straightforward. It becomes relevant once you start splitting logic across multiple base chains on the same hook, which is a more advanced pattern than this guide covers.

Persistence

If you used the config file above, the rules are already stored in /etc/nftables.conf. Just make sure nftables loads them at boot: sudo systemctl enable nftables. If you built rules with individual nft add commands instead, save them first:

# Save the active ruleset to the config file nftables loads on boot
sudo cp /etc/nftables.conf /etc/nftables.conf.bak
sudo sh -c 'printf "#!/usr/sbin/nft -f\nflush ruleset\n" > /etc/nftables.conf && nft list ruleset >> /etc/nftables.conf'
sudo systemctl enable nftables

The previous command replaces /etc/nftables.conf with the current active ruleset. It also includes flush ruleset, so don’t use it blindly on a host where Docker, Fail2ban, or other software manages nftables rules.

Removing a rule

nftables doesn’t let you delete by re-typing the rule the way iptables does — every rule gets an internal handle (an ID number) the moment it’s added, and you delete by handle. List the ruleset with handles shown, then delete:

sudo nft -a list ruleset
sudo nft delete rule inet filter input handle 4

If you want the whole chain gone rather than one rule in it, flush and delete the chain:

sudo nft 'flush chain inet filter input; delete chain inet filter input'

Warning: running nft flush chain as its own command on a chain with policy drop locks you out over SSH: it deletes the rule that lets your session through, but the drop policy stays. That’s why the command above runs flush and delete in one transaction. Once the chain is deleted, the server has no firewall for incoming traffic and every port is reachable, so create the replacement chain and rules immediately.

As with adding rules, re-save to /etc/nftables.conf afterward if you want the change to survive a reboot.

Pros: cleaner syntax, actively developed, one tool instead of separate IPv4/IPv6 commands, the direction the ecosystem is actually moving.

Cons: less legacy documentation floating around compared to iptables — when you hit an edge case, you’ll find fewer forum threads to lean on.

Side-by-side: the same rule, three ways

Feature UFW iptables nftables
IPv4 + IPv6 handles both iptables + ip6tables inet can handle both
Default deny incoming ufw default deny incoming iptables -P INPUT DROP nft ... chain ... { policy drop; }
Allow SSH (port 2222) ufw allow 2222/tcp iptables -A INPUT -p tcp --dport 2222 -j ACCEPT nft add rule inet filter input tcp dport 2222 accept
Allow HTTP/HTTPS ufw allow 80,443/tcp iptables -A INPUT -p tcp --dport 80 -j ACCEPT + same for 443 nft add rule inet filter input tcp dport { 80, 443 } accept
Check status ufw status verbose iptables -L -v nft list ruleset
Remove a rule ufw delete allow 2222/tcp iptables -D INPUT 3 (by line number) nft delete rule inet filter input handle 4

The nftables column shows the command-line form; the config file earlier expresses the same rules in file syntax.

Seeing the same rules side by side makes the differences in syntax and abstraction much easier to understand.

Which one should you actually use?

One important caution: don’t run UFW alongside raw iptables or nftables rules you’ve added by hand. UFW manages its own firewall rules, and manually added iptables or nftables rules can interact unpredictably with rules managed by UFW. Pick one layer to own your firewall policy.

Testing your rules safely

The same rule from the Fail2ban guide applies here, doubly so: a firewall misconfiguration doesn’t ban an IP, it can lock out every IP — including you.

# From another machine
nc -zv YOUR_SERVER 2222
nc -zv YOUR_SERVER 443

Just as important: confirm a port you didn’t explicitly allow in your firewall rules is actually blocked. Testing a port with nothing listening on it doesn’t prove much — the connection would fail on its own either way. To test the firewall itself, put something on the server side first, then confirm it’s still unreachable from outside:

# On the server: start a listener on a port your firewall does NOT allow
nc -l 3306
# From another machine:
# with DROP, this should typically time out;
# with REJECT, it should fail immediately.
# if it connects, something in your ruleset is allowing traffic you
# didn't intend to allow
nc -zv YOUR_SERVER 3306

Wrap-up

Fail2ban reacts to abuse in progress; your firewall decides what’s reachable in the first place. Neither one replaces the other. Fail2ban works by applying targeted firewall rules or actions to block specific offending IPs — but that’s not the same as a default-deny baseline that only exposes the ports you actually intend to. Without that baseline, a service like a database or an internal admin panel stays reachable to anyone who isn’t currently banned. Run both: a firewall that only opens what’s needed, and Fail2ban to react to abuse on top of it.

In short

Whichever you choose, use one tool as the owner of your firewall policy rather than mixing independently managed rulesets.

Next, audit a live server for weak spots with Lynis: How to Audit and Harden a Linux Server with Lynis.


Discover more from vigilnix

Subscribe to get the latest posts sent to your email.

Ismaël Qouiqa Avatar

Written by

2 responses to “UFW vs iptables vs nftables: Which Linux Firewall Should You Use?”

  1. […] There’s no rule for 11434 (except on the VPN interface, if you chose that). More on UFW in UFW vs iptables vs nftables. […]

  2. […] For more complex rules, iptables or nftables can be used directly — we compare them with UFW in UFW vs iptables vs nftables: Which Linux Firewall Should You Use? […]

Leave a Reply