Skip to main content

Web servers and networking · Advanced · 20 min

Write a server firewall with nftables

By Padding · Updated 18 Nov 2026
Ubuntu 26.04.1 LTS · nftables 1.1.6

You will write one /etc/nftables.conf with a default-drop input chain, rate-limited SSH, named address sets, counters and logging, and load it over SSH behind a timer that undoes it if you lose your connection.

On this page

UFW is a good front door, but sooner or later you need to see and own the rules the kernel actually runs: to rate-limit SSH per address, keep a list of trusted addresses you can change without a reload, or understand why Docker's published ports ignore your firewall. On Ubuntu 26.04 all of that lives in nftables, the kernel's packet filter and its nft command.

In this tutorial you will write a complete host firewall as one file, /etc/nftables.conf, check it before it touches the kernel, and load it over SSH with a safety timer that removes it again if you lock yourself out. The firewall is for a single web server: it drops everything incoming except replies, loopback, the ICMP messages IPv4 and IPv6 need, SSH and the web ports.

A few words first, because nftables uses them precisely:

  • A table is a container for chains and sets. Its family says which traffic it sees: ip (IPv4), ip6 (IPv6) or inet (both). You will use one inet table, so each rule covers both protocols.
  • A chain holds rules that run in order. A base chain is attached to a hook, a point in the kernel's packet path: input for packets addressed to this machine, forward for packets passing through it, output for packets it sends.
  • A priority orders base chains on the same hook. Lower numbers run first; the name filter means 0.
  • A policy is what happens to a packet that reaches the end of a base chain without a verdict: accept or drop.

Step 1 · Install nftables and look at what is loaded

Install the package, which gives you the nft command and a service that loads /etc/nftables.conf at boot:

Bash
sudo apt update
sudo apt install -y nftables
nft --version

Now list everything the kernel has loaded. This needs root:

Bash
sudo nft list ruleset
sudo iptables -V
sudo ufw status

Check it worked

nft --version prints something like nftables v1.1.6 (Commodore Bullwinkle #4). On a fresh server with UFW off, sudo nft list ruleset prints nothing. If UFW is active, you will see tables such as table ip filter and table ip6 filter with chains named ufw-before-input and similar. They are there because iptables -V reports (nf_tables): on Ubuntu the iptables command is a translator that writes nftables rules. UFW, Docker and your own file all end up in the same ruleset, and the last step deals with that.

Step 2 · Write the ruleset file

Ubuntu ships a sample /etc/nftables.conf that starts with flush ruleset. That line deletes every table in the kernel, including the ones UFW and Docker created, each time the file loads. The file below replaces only its own table, named host_firewall.

Writing the file changes nothing in the kernel yet. Keep a copy of the sample, then write yours:

Bash
sudo cp /etc/nftables.conf /etc/nftables.conf.orig
sudo tee /etc/nftables.conf > /dev/null <<'EOF'
#!/usr/sbin/nft -f
# Host firewall. Check with: sudo nft -c -f /etc/nftables.conf
# Only the inet host_firewall table is replaced; tables made by UFW or Docker are left alone.

# Create the table if it is missing, then delete it, so the definition below starts clean.
table inet host_firewall
delete table inet host_firewall

table inet host_firewall {
    # Trusted addresses for SSH. Replace these documentation ranges with your own.
    set admin_v4 {
        type ipv4_addr
        flags interval
        elements = { 192.0.2.10, 198.51.100.0/24 }
    }

    set admin_v6 {
        type ipv6_addr
        flags interval
        elements = { 2001:db8::/32 }
    }

    # Filled by the kernel: one entry per source address opening SSH connections.
    set ssh_flood_v4 {
        type ipv4_addr
        flags dynamic
        timeout 5m
        size 65536
    }

    set ssh_flood_v6 {
        type ipv6_addr
        flags dynamic
        timeout 5m
        size 65536
    }

    chain input {
        type filter hook input priority filter; policy drop;

        ct state invalid counter drop comment "broken or unknown connection state"
        ct state { established, related } accept comment "replies to traffic already allowed"
        iif "lo" accept comment "loopback"

        icmp type { echo-request, destination-unreachable, time-exceeded, parameter-problem } accept comment "ICMP for IPv4"
        icmpv6 type { destination-unreachable, packet-too-big, time-exceeded, parameter-problem, echo-request, mld-listener-query, nd-router-solicit, nd-router-advert, nd-neighbor-solicit, nd-neighbor-advert } accept comment "ICMPv6 that IPv6 needs"

        tcp dport 22 ip saddr @admin_v4 counter accept comment "SSH from admin addresses"
        tcp dport 22 ip6 saddr @admin_v6 counter accept comment "SSH from admin addresses"
        tcp dport 22 ct state new update @ssh_flood_v4 { ip saddr limit rate over 10/minute burst 5 packets } counter drop comment "SSH flood, IPv4"
        tcp dport 22 ct state new update @ssh_flood_v6 { ip6 saddr limit rate over 10/minute burst 5 packets } counter drop comment "SSH flood, IPv6"
        tcp dport 22 counter accept comment "SSH from anywhere, under the limit"

        tcp dport { 80, 443 } counter accept comment "HTTP and HTTPS"
        udp dport 443 counter accept comment "HTTP/3 over QUIC"

        limit rate 10/minute burst 20 packets log prefix "nft input drop: " level info
        counter comment "dropped by the input policy"
    }

    chain forward {
        type filter hook forward priority filter; policy drop;
    }

    chain output {
        type filter hook output priority filter; policy accept;
    }
}
EOF

Read it from the top of the input chain, because rules run in order and the first verdict wins:

  1. Packets the connection tracker cannot place are dropped and counted. Everything that belongs to a connection you already allowed, including the ICMP errors related to it, is accepted next. This one rule carries most of the traffic, which is why it sits near the top.
  2. Loopback is always allowed; many services talk to each other over 127.0.0.1.
  3. ICMP is not optional. IPv6 cannot find neighbours or routers without the nd- types and breaks large transfers without packet-too-big. The list follows the host recommendations in RFC 4890.
  4. SSH from the admin_v4 or admin_v6 sets is accepted with no limit. Every other source may open 10 new SSH connections a minute, with a burst of 5. The update @ssh_flood_v4 { ip saddr limit rate over ... } statement keeps a separate limit per address in the dynamic set, so one noisy scanner does not use up everyone's allowance. update adds the address if it is missing and resets its 5-minute timeout on every new SSH attempt, so an entry only expires after 5 minutes of quiet from that address. (add would never refresh the timeout, letting a busy scanner start over with a fresh allowance every 5 minutes.)
  5. Web ports are open, including UDP 443 for HTTP/3.
  6. Whatever is left is logged at most 10 times a minute with the prefix `nft input drop: `, counted, and dropped by the policy.

The forward chain drops everything, which is right for a server that does not route. On a Docker host it blocks every container; the last step shows the change. If SSH listens on a port other than 22, change all five SSH rules.

Many people reach their servers from mobile data or a home connection whose public address changes and is shared through carrier-grade NAT, which is common on prepaid networks across Africa. That is why the trusted sets are an extra, not the only way in: if your address changes, you still reach SSH through the rate-limited rule.

Check it worked

Bash
grep -c 'tcp dport 22' /etc/nftables.conf
head -n 1 /etc/nftables.conf

The count is 5 and the first line is #!/usr/sbin/nft -f.

Step 3 · Check the file before it reaches the kernel

nft -c parses the file and asks the kernel to validate it without applying anything:

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

To see what a mistake looks like, write a small file with a typo in it:

Bash
mkdir -p ~/nft-demo
cat > ~/nft-demo/broken.nft <<'EOF'
table inet typo_demo {
    chain input {
        type filter hook input priority filter; policy accept;
        tcp dport 22 acept
    }
}
EOF
Bash
sudo nft -c -f ~/nft-demo/broken.nft

Then remove the demo:

Bash
rm -r ~/nft-demo

Check it worked

The real file prints nothing and the command exits with status 0 (echo $? shows 0). The broken one prints an error naming the file and line 4, something like broken.nft:4:27-27: Error: syntax error, unexpected newline, with a ^ at the end of tcp dport 22 acept, because nft did not recognise acept as a verdict and reached the end of the line still expecting one. Because nft -f loads a whole file as one transaction, a file that fails this way never half-applies: the kernel keeps the rules it had.

Step 4 · Write a loader with a rollback timer

A mistake in the SSH rules can cut you off the moment the file loads, and the session you are typing in may hang. Before you load anything over SSH, put a timer in place that undoes the change on its own. systemd-run creates the timer outside your login session, so it still fires if your connection drops.

The script saves the current host_firewall table, schedules its return, then loads the new file:

Bash
sudo tee /usr/local/sbin/nft-safe-apply > /dev/null <<'EOF'
#!/bin/sh
# nft-safe-apply: load the host_firewall table, and undo it unless confirmed in time.
# Usage: sudo nft-safe-apply [file] [seconds]
set -eu

conf=${1:-/etc/nftables.conf}
wait_seconds=${2:-120}
state_dir=/var/lib/nft-safe-apply
previous=$state_dir/previous.nft

if [ "$(id -u)" -ne 0 ]; then
  echo "Run this with sudo." >&2
  exit 1
fi

nft -c -f "$conf"

umask 077
mkdir -p "$state_dir"
if nft -s list table inet host_firewall > "$previous" 2> /dev/null; then
  echo "Saved the current host_firewall table to $previous"
else
  : > "$previous"
  echo "No host_firewall table loaded yet; a rollback removes the new one."
fi

systemd-run --quiet --unit=nft-rollback --on-active="$wait_seconds" \
  /bin/sh -c "nft delete table inet host_firewall 2> /dev/null; if [ -s $previous ]; then nft -f $previous; fi"

nft -f "$conf"
echo "Loaded $conf. It is removed again in $wait_seconds seconds."
echo "Open a NEW SSH session now. If it connects, keep the rules with:"
echo "  sudo systemctl stop nft-rollback.timer"
EOF
sudo chmod 755 /usr/local/sbin/nft-safe-apply

The rollback deletes only host_firewall and puts back the earlier version if there was one. It never flushes the whole ruleset, so UFW and Docker rules survive it. If a rollback from an earlier run is still pending, systemd-run refuses the duplicate unit name and the script stops before loading anything.

Check it worked

Bash
sh -n /usr/local/sbin/nft-safe-apply && echo "syntax OK"
ls -l /usr/local/sbin/nft-safe-apply

You see syntax OK and the file mode -rwxr-xr-x, owned by root.

Step 5 · Load the firewall over SSH

Before you run the next command, keep your current SSH session open and have your provider's console ready. If UFW is active, read the last step first: two firewalls on the same hook both have to accept a packet.

Load the file with a two-minute rollback:

Bash
sudo nft-safe-apply /etc/nftables.conf 120
sudo systemctl list-timers nft-rollback.timer

Without closing the first session, open a second terminal on your laptop and connect again. Replace you@server.example with your own login:

Bash
# On your laptop
ssh you@server.example

If the new session connects, keep the rules from either session:

Bash
sudo systemctl stop nft-rollback.timer

If it does not connect, do nothing. When the timer fires, the old table returns and you can fix the file and try again.

Check it worked

list-timers shows nft-rollback.timer with a time left of under two minutes until you stop it. Then look at the loaded chain with its counters:

Bash
sudo nft list chain inet host_firewall input

The rule tcp dport 22 counter packets ... accept comment "SSH from anywhere, under the limit" shows a packet count above 0, from your second session. From your laptop, a port with no rule is now silent rather than refused:

Bash
# On your laptop; replace server.example with your server
nc -zv -w 3 server.example 5432

nc times out instead of reporting Connection refused, because the packet is dropped.

Step 6 · Change sets live and read the logs

Named sets can change without reloading the table. Add a trusted address for SSH (replace 203.0.113.25 with yours):

Bash
sudo nft add element inet host_firewall admin_v4 '{ 203.0.113.25 }'
sudo nft list set inet host_firewall admin_v4

A change made this way lasts until the next load or reboot. Add the same address to elements in /etc/nftables.conf so the file stays the source of truth.

Look at who is being rate-limited, and at what the policy dropped:

Bash
sudo nft list set inet host_firewall ssh_flood_v4
sudo journalctl -k -g 'nft input drop' --since '15 min ago'

Check it worked

The admin_v4 listing includes 203.0.113.25 next to the ranges from the file. The ssh_flood_v4 set lists recent SSH sources, each with an expires time and its limit state. The journal shows kernel lines starting nft input drop: ` with `SRC=, DST=, PROTO= and DPT= fields; on a public server, scanners usually produce some within minutes.

Step 7 · Load the firewall at boot

The nftables service loads /etc/nftables.conf when the server starts. Turn it on:

Bash
sudo systemctl enable nftables
systemctl is-enabled nftables
systemctl cat nftables

Read the ExecStop and ExecReload lines in that output. If ExecStop runs nft flush ruleset, then stopping or restarting the service wipes every table, including Docker's and UFW's. Apply later changes with sudo nft-safe-apply instead of restarting the service.

Check it worked

is-enabled prints enabled. After your next planned reboot, sudo nft list table inet host_firewall shows the table without you loading it.

Step 8 · Live alongside UFW and Docker

Everything on Ubuntu shares one netfilter. Each base chain on the input hook runs in priority order, and a packet must survive all of them. An accept ends only the chain it is in; a drop anywhere is final. So with UFW active and your table loaded, a port must be open in both. Pick one owner for the host's input rules. If you choose this file, turn UFW off once your table is loaded and confirmed:

Bash
sudo ufw disable

Docker writes its own tables through iptables. A published port (-p 8080:80) is rewritten in the nat table before the input hook, so the packet goes to the container through the forward hook. Two things follow:

  • Your input chain never sees traffic to published container ports. To keep a container private, publish it on loopback only, such as -p 127.0.0.1:8080:80, and put Nginx or Caddy in front.
  • Your forward chain with policy drop blocks container traffic. On a Docker host, change that chain in /etc/nftables.conf to this, then load it with sudo nft-safe-apply:
Text
    chain forward {
        type filter hook forward priority filter; policy accept;
    }

Docker Engine also has an experimental nftables backend; until you adopt it, leave Docker's tables alone and never edit them with nft.

Check it worked

sudo ufw status prints Status: inactive, and sudo nft list tables still lists table inet host_firewall. On a Docker host, a container started with -p 127.0.0.1:8080:80 answers curl http://127.0.0.1:8080 on the server, and the same port does not answer from your laptop.

Next steps

  • Compare this file with what UFW generates in /tutorials/set-up-ufw-firewall-ubuntu-26-04.
  • Take UFW further, with app profiles and logging, in /tutorials/go-further-with-ufw-profiles-rate-limits-and-logging.
  • Install Docker and see its tables appear in sudo nft list ruleset with /tutorials/install-docker-engine-on-ubuntu-26-04.
  • Write tighter address sets with /tutorials/understand-ip-addresses-subnets-and-cidr.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.