On current Debian and Ubuntu, nftables is the packet filter underneath everything. iptables is a compatibility layer on top of it, and ufw generates rules for it. Writing the ruleset yourself gives you one readable file, native IPv4 and IPv6 handling in a single table, and features like sets and per-IP rate limits without extra tools.

This guide builds a complete input firewall for a typical VPS (SSH plus a web server) and, most importantly, applies it in a way that cannot lock you out.

0. Before you start

  • Keep a console open as a fallback: the provider's VNC or KVM console, if you have one.
  • Know your own public IP (curl -4 ifconfig.me from your laptop).
  • Use one firewall manager. If ufw or firewalld is active, they fight over the same rules. Turn ufw off first:
sudo ufw status sudo ufw disable sudo apt purge -y ufw # optional, avoids confusion later sudo apt install -y nftables 

1. The ruleset

The inet family handles IPv4 and IPv6 in one table. Edit /etc/nftables.conf:

#!/usr/sbin/nft -f flush ruleset table inet filter { # Addresses that may always reach SSH (yours). Edit these. set admin4 { type ipv4_addr flags interval elements = { 203.0.113.10, 198.51.100.0/24 } } # Per-IP SSH rate tracking, entries expire after 5 minutes set ssh_rate4 { type ipv4_addr flags dynamic, timeout timeout 5m } set ssh_rate6 { type ipv6_addr flags dynamic, timeout timeout 5m } chain input { type filter hook input priority filter; policy drop; ct state invalid drop ct state { established, related } accept iif "lo" accept # ICMP: ping and the error messages that make TCP work well ip protocol icmp icmp type { echo-request, destination-unreachable, time-exceeded, parameter-problem } accept # ICMPv6: IPv6 does not work without neighbor discovery ip6 nexthdr ipv6-icmp icmpv6 type { echo-request, destination-unreachable, packet-too-big, time-exceeded, parameter-problem, nd-router-advert, nd-neighbor-solicit, nd-neighbor-advert } accept # SSH: allow-listed IPs always, everyone else rate limited ip saddr @admin4 tcp dport 22 accept tcp dport 22 ct state new update @ssh_rate4 { ip saddr limit rate over 10/minute burst 5 packets } drop tcp dport 22 ct state new update @ssh_rate6 { ip6 saddr limit rate over 10/minute burst 5 packets } drop tcp dport 22 accept # Web: HTTP, HTTPS and HTTP/3 (QUIC) tcp dport { 80, 443 } accept udp dport 443 accept # Log a sample of what gets dropped limit rate 5/minute log prefix "nft-drop: " level info } chain forward { type filter hook forward priority filter; policy drop; } chain output { type filter hook output priority filter; policy accept; } } 

What each block does, and why:

  • policy drop on input: anything not explicitly allowed is dropped.
  • ct state established,related accept comes early: replies to connections the server opened (apt, DNS, outgoing API calls) and packets of already-accepted connections pass with one cheap lookup. Without it, the server cannot even resolve DNS.
  • ct state invalid drop: packets that match no known connection state, a common sign of scans.
  • iif "lo": local services talking to each other over 127.0.0.1/::1.
  • ICMPv6 neighbor discovery is not optional. nd-neighbor-solicit and nd-neighbor-advert are IPv6's version of ARP. Block them and IPv6 on the server stops working, often minutes later, when the neighbor cache expires. packet-too-big is needed for path MTU discovery; without it some connections hang on large transfers.
  • SSH rate limit: the update @ssh_rate4 { ip saddr limit rate over 10/minute ... } drop rule tracks each source address in a dynamic set. An address that opens more than 10 new SSH connections a minute (after a burst of 5) gets its new connections dropped. Established sessions are not affected because they were accepted higher up. Your allow-listed addresses skip the limit entirely.
  • forward drop: this server is not a router. If you later run WireGuard or containers, this chain needs rules.

Change the SSH port number in all three SSH lines if you moved sshd. Add more ports the same way, for example udp dport 51820 accept for WireGuard.

2. Check the syntax without applying it

sudo nft -c -f /etc/nftables.conf && echo "syntax OK" 

-c parses and validates the whole file against the kernel without committing anything.

3. Apply it with an automatic rollback

This is the step that saves you a trip to the console. Schedule a rule flush in two minutes, then load the ruleset:

sudo systemd-run --on-active=120 --unit=nft-rollback /usr/sbin/nft flush ruleset sudo nft -f /etc/nftables.conf 

Now open a new terminal and start a fresh SSH session. Check that the website still answers.

  • If everything works, cancel the rollback:
sudo systemctl stop nft-rollback.timer 
  • If you are locked out, wait two minutes. The timer removes all rules, the server is reachable again, and you can fix the file.

systemd-run --on-active creates a transient timer, so no extra package is needed. (at works too, if you have it installed.)

4. Make it permanent

sudo systemctl enable --now nftables sudo nft list ruleset 

The nftables service loads /etc/nftables.conf at boot. After every edit: nft -c -f, then the rollback-and-apply sequence again.

5. Day-to-day operations

Add an address to the SSH allow-list without reloading anything:

sudo nft add element inet filter admin4 '{ 192.0.2.44 }' 

That change lasts until the next reload, so put it in the file as well.

See which IPs are currently being rate limited:

sudo nft list set inet filter ssh_rate4 

Count what a rule matches by adding counter to it, for example tcp dport { 80, 443 } counter accept, then read the numbers with sudo nft list chain inet filter input.

Read the drop log:

sudo journalctl -k -g nft-drop --since "1 hour ago" 

Need SSH from the allow-list only? Delete the three generic SSH lines below the @admin4 rule. Only do this if your IP is fixed, and keep console access.

6. Docker and other rule writers

Docker writes its own rules (through iptables-nft) into separate tables. Two consequences:

  1. flush ruleset at the top of the file also wipes Docker's rules when you reload. Run sudo systemctl restart docker after reloading nftables, or Docker containers lose network access.
  2. Published container ports bypass your input chain. Docker handles them in its own forward and NAT rules, so a ports: "8080:8080" line is reachable from the internet whatever your input chain says. Bind container ports to localhost ("127.0.0.1:8080:8080") and expose them through a reverse proxy.

fail2ban works with nftables too: set banaction = nftables-multiport in /etc/fail2ban/jail.local. It creates its own table, so your file does not need changes.

7. Quick tests from outside

From your laptop:

nc -vz -w 5 YOUR_SERVER_IP 22 # should connect nc -vz -w 5 YOUR_SERVER_IP 3306 # should time out (dropped) ping -c 3 YOUR_SERVER_IP # should answer ping -6 -c 3 YOUR_SERVER_IPV6 # if you have IPv6 

A timeout on a closed port is what drop looks like from outside. If you prefer that scanners get an immediate refusal, end the chain with reject instead of relying on the policy, at the cost of confirming the host exists.

Prefer something simpler?

If you just want sensible defaults on a fresh server, the open-source vps-first-steps script sets up ufw, fail2ban, safer SSH and automatic security updates in one readable run, and it is maintained by the team behind PhantomVPS, where I work. PhantomVPS plans come with root access, so either approach works, and sign-up needs no ID documents and no phone number.