Debian 11: nftables

nftables is the packet filter of modern Linux. It replaced iptables, ip6tables, arptables and ebtables with one framework and one tool, nft. One ruleset covers IPv4 and IPv6 at once, sets and maps are built in, and a whole ruleset loads atomically: either all of it, or none of it.

This guide builds a host firewall for a server with two network cards: one in the DMZ that serves the public, and one on the internal network for management, monitoring and backends. Each interface gets its own policy. At the end there’s a section on what you need when the host also runs Docker.

What you’ll end up with:

  • Default deny inbound and forwarded, in a single inet table for IPv4 and IPv6
  • A separate policy per interface, using a verdict map, so the DMZ can never reach SSH or the exporters
  • Reverse path filtering for IPv4 and IPv6, which stops spoofed sources on a multi-homed host
  • ICMPv6 done right (IPv6 breaks without it) and rate-limited ping
  • Per-source SSH rate limiting with a dynamic set, so one attacker can’t lock out your admins
  • Named sets for admin and monitoring addresses that you can change at runtime
  • Rate-limited logging, without the broadcast noise
  • Optional egress filtering for the DMZ host
  • Safe loading with automatic rollback, so a typo doesn’t lock you out
  • A ruleset that never touches other tables, so Docker, Fail2Ban and CrowdSec keep working

Tested on: Debian 13 “trixie” with nftables 1.1 and kernel 6.12. All commands run as root (or with sudo).


Table of contents

  1. Placeholders
  2. How nftables decides: five things to know
  3. Install and enable
  4. The example host
  5. The complete ruleset
  6. The ruleset explained
  7. Optional: egress filtering
  8. Loading safely with automatic rollback
  9. Testing and debugging
  10. Living together with Fail2Ban and CrowdSec
  11. Running Docker on the same host
  12. Day-2 operations
  13. Troubleshooting
  14. Checklist

1. Placeholders

PlaceholderMeaning
www-01The server
ens192Internal interface: 10.20.10.21/24, 2001:db8:10::21/64
ens224DMZ interface: 172.30.20.21/24, 2001:db8:20::21/64, default gateway 172.30.20.1
10.20.0.0/24, 2001:db8:1::/64Admin network, reached through the internal router 10.20.10.1
10.20.0.112, 2001:db8:1::112Prometheus server
172.30.20.22The second web node (keepalived/VRRP partner)
10.20.0.53Internal DNS resolver
10.20.0.30:3128Internal web proxy (Squid), also used for apt
10.20.0.25Internal SMTP relay

Replace them with your own values. Interface names come from ip -br link.


2. How nftables decides: five things to know

Most firewall mistakes come from misunderstanding one of these.

1. Tables are just containers, and they belong to someone. A table has a family: ip (IPv4), ip6, inet (both), arp, bridge or netdev. Your rules, Docker’s rules, Fail2Ban’s bans and CrowdSec’s blocklists each live in their own table. That’s why you must never run flush ruleset on a host where other tools manage tables. It deletes their tables too.

2. Base chains hook into the kernel, regular chains are subroutines. A base chain has type filter hook input priority filter; policy drop; and sees packets. A regular chain has no hook and only sees what you jump to it. When the regular chain ends without a verdict, the packet returns to where it jumped from.

3. drop is final, accept is not. Several tables can hook into the same point (for example input). The kernel runs them in priority order. If any base chain drops a packet, it’s gone. If one accepts it, the packet continues to the next base chain at the same hook, which can still drop it. Remember this for Fail2Ban (section 10) and Docker (section 11).

4. Connection tracking does most of the work. ct state established,related accepts replies to connections that were already allowed. So you only write rules for the first packet of a connection. Everything after that is one cheap lookup.

5. Sets and maps replace long rule lists. tcp dport { 80, 443 } is one hash lookup, not two rules. Named sets can be changed at runtime (nft add element ...). Verdict maps (vmap) send a packet to a chain by key, for example by interface.


3. Install and enable

nftables is Debian’s default firewall framework. The iptables command on Debian 13 is also only a front end (iptables-nft) that writes nftables rules.

apt update
apt install nftables
systemctl enable nftables
nft --version

The service loads /etc/nftables.conf at boot, before the network comes up.

Debian’s unit has a trap. Check what stop and restart do:

systemctl cat nftables | grep -E 'Exec(Start|Reload|Stop)='Code language: JavaScript (javascript)

ExecStop runs nft flush ruleset. That means systemctl restart nftables (or stop) wipes every table on the host, including Docker’s and Fail2Ban’s. Make stop remove only your own table:

mkdir -p /etc/systemd/system/nftables.service.d
cat > /etc/systemd/system/nftables.service.d/override.conf <<'EOF'
[Service]
ExecStop=
ExecStop=/usr/sbin/nft destroy table inet filter
EOF
systemctl daemon-reloadCode language: JavaScript (javascript)

And get into the habit of using systemctl reload nftables (or the script in section 8), never restart.


4. The example host

www-01 is a public web server. The edge firewall forwards ports 80 and 443 to its DMZ address. A second node, 172.30.20.22, shares a virtual IP with it through keepalived. Management happens over the internal leg.

InterfaceInbound allowedFrom
ens224 (DMZ)HTTP, HTTPSAnywhere
ens224 (DMZ)VRRP (keepalived)The partner node only
ens192 (internal)SSHAdmin network only, rate-limited per address
ens192 (internal)Node exporter 9100, Apache exporter 9117Prometheus only
ens192 (internal)IGMP queriesThe switch
BothEssential ICMP/ICMPv6, rate-limited pingAnywhere
Anything elseNothingLogged (rate-limited) and dropped
ForwardingNothingThe host is not a router

The default route points to the DMZ. The internal leg has a static route to the admin network:

ip route
# default via 172.30.20.1 dev ens224
# 10.20.0.0/24 via 10.20.10.1 dev ens192
# 10.20.10.0/24 dev ens192 proto kernel scope link src 10.20.10.21
# 172.30.20.0/24 dev ens224 proto kernel scope link src 172.30.20.21Code language: PHP (php)

That route matters. Without it, replies to the admin network would leave through the DMZ, and the reverse path filter (section 6.1) would drop SSH from your admins. Set it in /etc/network/interfaces (up ip route add ...) or in your systemd-networkd .network file, and the IPv6 one too.


5. The complete ruleset

Create /etc/nftables.conf:

#!/usr/sbin/nft -f
# /etc/nftables.conf - host firewall for www-01
# DMZ web server with an internal management leg.
#
# Only our own table is replaced on every load. Tables that belong to
# Docker, Fail2Ban or CrowdSec are left alone: never "flush ruleset" here.

define LAN_IF    = "ens192"         # internal: management, monitoring, backends
define DMZ_IF    = "ens224"         # DMZ: public web traffic, default route
define VRRP_PEER = 172.30.20.22     # second web node (keepalived)

destroy table inet filter

table inet filter {

    # ---------- who may do what ----------

    set admin_v4 {
        type ipv4_addr
        flags interval
        elements = { 10.20.0.0/24 }
    }
    set admin_v6 {
        type ipv6_addr
        flags interval
        elements = { 2001:db8:1::/64 }
    }
    set monitor_v4 {
        type ipv4_addr
        elements = { 10.20.0.112 }
    }
    set monitor_v6 {
        type ipv6_addr
        elements = { 2001:db8:1::112 }
    }

    # per-source SSH rate limiting, filled by the rules themselves
    set ssh_meter_v4 {
        type ipv4_addr
        size 65535
        flags dynamic,timeout
        timeout 5m
    }
    set ssh_meter_v6 {
        type ipv6_addr
        size 65535
        flags dynamic,timeout
        timeout 5m
    }

    # ---------- before routing: anti-spoofing ----------

    chain prerouting {
        type filter hook prerouting priority raw; policy accept;

        # DHCP replies arrive before the interface has an address
        udp sport 67 udp dport 68 accept

        # reverse path filter: drop packets whose source address would not
        # be routed back out of the interface they arrived on
        meta nfproto ipv4 fib saddr . iif oif missing counter drop
        ip6 saddr != :: fib saddr . iif oif missing counter drop
    }

    # ---------- traffic to this host ----------

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

        # replies to allowed connections in, broken packets out
        ct state vmap { established : accept, related : accept, invalid : drop }

        # a new TCP connection must start with a plain SYN
        ct state new tcp flags & (fin | syn | rst | ack) != syn counter drop

        # loopback, and loopback addresses only on loopback
        iifname "lo" accept
        ip daddr 127.0.0.0/8 counter drop
        ip6 daddr ::1 counter drop

        # ICMP and ICMPv6 for every interface
        jump icmp_in

        # one policy per interface
        iifname vmap { $LAN_IF : jump input_lan, $DMZ_IF : jump input_dmz }

        # whatever is left: drop broadcast/multicast noise silently, log the rest
        meta pkttype { broadcast, multicast } drop
        limit rate 10/minute burst 20 packets log prefix "nft input drop: " level info
    }

    chain icmp_in {
        # ICMPv6 that IPv6 cannot work without (RFC 4890)
        icmpv6 type { destination-unreachable, packet-too-big, time-exceeded, parameter-problem } accept
        icmpv6 type { nd-router-solicit, nd-router-advert, nd-neighbor-solicit, nd-neighbor-advert } ip6 hoplimit 255 accept
        icmpv6 type { mld-listener-query, mld-listener-report, mld-listener-done, mld2-listener-report } ip6 saddr fe80::/10 accept
        icmpv6 type echo-request limit rate 10/second burst 20 packets accept

        # ICMPv4: errors (path MTU discovery needs them) and rate-limited ping
        icmp type { destination-unreachable, time-exceeded, parameter-problem } accept
        icmp type echo-request limit rate 10/second burst 20 packets accept

        # all other ICMP (redirects, excess pings, ...) is dropped without logging
        meta l4proto { icmp, ipv6-icmp } counter drop
    }

    chain input_lan {
        # SSH from the admin network only, rate-limited per source address
        tcp dport 22 ip saddr @admin_v4 jump ssh_in
        tcp dport 22 ip6 saddr @admin_v6 jump ssh_in

        # Prometheus scrapes: node exporter, Apache exporter
        tcp dport { 9100, 9117 } ip saddr @monitor_v4 accept
        tcp dport { 9100, 9117 } ip6 saddr @monitor_v6 accept

        # IGMP general queries from the switch (keeps IGMP snooping happy)
        ip protocol igmp ip daddr 224.0.0.1 accept
    }

    chain input_dmz {
        # the public service
        tcp dport { 80, 443 } accept
        # udp dport 443 accept          # HTTP/3, only if the web server speaks QUIC

        # keepalived: VRRP (protocol 112) from the partner node only
        ip saddr $VRRP_PEER ip daddr 224.0.0.18 ip protocol 112 accept
    }

    chain ssh_in {
        # more than 10 new connections per minute from one address: drop
        update @ssh_meter_v4 { ip saddr limit rate over 10/minute burst 5 packets } counter drop
        update @ssh_meter_v6 { ip6 saddr limit rate over 10/minute burst 5 packets } counter drop
        accept
    }

    # ---------- traffic through this host ----------

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

        # this host is not a router (for Docker, see section 11)
        limit rate 10/minute burst 20 packets log prefix "nft forward drop: " level info
    }

    # ---------- traffic from this host ----------

    chain output {
        type filter hook output priority filter; policy accept;
        # for egress filtering, see section 7
    }
}

# other tables of your own, one file per table, each starting with
# its own "destroy table ..."
include "/etc/nftables.d/*.nft"Code language: PHP (php)

Check it without changing anything, then load it the safe way (section 8):

mkdir -p /etc/nftables.d
nft -c -f /etc/nftables.conf && echo "syntax OK"Code language: PHP (php)

6. The ruleset explained

6.1 Replacing only our own table

destroy table inet filter
table inet filter { ... }

destroy table deletes the table if it exists and does nothing if it doesn’t. The whole file is one transaction, so there’s never a moment without a firewall. Don’t use flush ruleset, which is in Debian’s example file: it also deletes Docker’s, Fail2Ban’s and CrowdSec’s tables. destroy needs nftables 1.0.8 and kernel 6.3, which Debian 13 has.

6.2 Interfaces by name: iifname, not iif

iif stores the interface’s index when the rules load, so the interface must exist then. nftables loads before the network, and interfaces like docker0, br-*, VLANs or WireGuard can come and go. iifname compares the name at packet time and also supports wildcards like "br-*". It’s slightly slower, which you’ll never notice on a host firewall.

6.3 Reverse path filtering on a multi-homed host

meta nfproto ipv4 fib saddr . iif oif missing counter drop
ip6 saddr != :: fib saddr . iif oif missing counter drop

For every incoming packet, the kernel looks up the route back to the source address on the interface the packet came in on. If there is none, the source is spoofed or the routing is asymmetric, and the packet is dropped. That stops someone in the DMZ from sending packets with a source address from your admin network.

The rp_filter sysctl only does this for IPv4. This rule covers IPv6 as well. The :: exception lets IPv6 duplicate address detection through, and the DHCP rule lets a DHCP client get its first lease.

On a multi-homed host this requires correct routes. If the admin network has no route via ens192, the filter drops your SSH sessions. Watch the counter: nft list chain inet filter prerouting.

6.4 Connection tracking first

ct state vmap { established : accept, related : accept, invalid : drop }
ct state new tcp flags & (fin | syn | rst | ack) != syn counter dropCode language: JavaScript (javascript)

The first rule handles almost all traffic in one lookup. related covers, for example, ICMP errors for an existing connection. The second rule drops “new” TCP packets that aren’t a plain SYN, such as stealth scans (FIN, NULL, Xmas) and leftovers of connections that conntrack forgot.

6.5 ICMP: don’t break IPv6

IPv6 doesn’t work without ICMPv6. Neighbour Discovery replaces ARP, Router Advertisements provide the default route with SLAAC, and Packet Too Big is the only way path MTU discovery works. IPv6 routers never fragment.

  • ip6 hoplimit 255 on Neighbour Discovery guarantees that the packet came from the local link. A router would have decremented it.
  • MLD only comes from link-local addresses.
  • Ping is allowed but rate-limited. Excess and every other ICMP type are dropped quietly in the same chain, so they don’t flood the log.

Write icmpv6 type ..., not ip6 nexthdr icmpv6 icmpv6 type .... MLD packets carry a hop-by-hop extension header, so nexthdr isn’t ICMPv6 for them. icmpv6 type finds the real transport header even behind extension headers.

6.6 One policy per interface with a verdict map

iifname vmap { $LAN_IF : jump input_lan, $DMZ_IF : jump input_dmz }Code language: PHP (php)

A packet from the DMZ only ever sees input_dmz. No rule in input_lan can be reached from the DMZ by mistake, however you change it later. When a per-interface chain ends without a verdict, the packet returns to input, gets logged and is dropped by the policy.

A third interface (a backup VLAN, for example) is one more entry in the map and one more chain.

6.7 SSH: rate limiting per source, not globally

update @ssh_meter_v4 { ip saddr limit rate over 10/minute burst 5 packets } counter drop

Every source address gets its own entry in the dynamic set, with its own rate limit. Entries expire after 5 minutes. Compare this with a global limit rate 7/minute ... accept: one bot on the internet uses up those 7 connections a minute, and your admins can’t log in any more.

SSH is only reachable from the admin network anyway. The limit protects against a compromised machine there, and it’s the pattern to use if you ever have to open SSH more widely. Fail2Ban (section 10) adds bans based on actual failed logins.

6.8 VRRP for keepalived

ip saddr $VRRP_PEER ip daddr 224.0.0.18 ip protocol 112 acceptCode language: PHP (php)

VRRP isn’t TCP or UDP, it’s IP protocol 112 sent to the multicast group 224.0.0.18. Allow it only from the partner. Anyone else on the segment who can send VRRP could otherwise take over your virtual IP. Use keepalived’s authentication or, better, unicast peers on top.

6.9 Logging without flooding the journal

meta pkttype { broadcast, multicast } drop
limit rate 10/minute burst 20 packets log prefix "nft input drop: " level infoCode language: JavaScript (javascript)

Broadcasts and multicasts (DHCP discovers from other machines, mDNS, NetBIOS, SSDP) would fill the log with noise, so they’re dropped silently first. The rest is logged, but never more than 10 lines a minute. An unlimited log rule lets anyone with a port scanner fill your disk.

Read the log with:

journalctl -k -g 'nft (input|forward) drop' --since -1hCode language: JavaScript (javascript)

6.10 Forwarding: drop

www-01 doesn’t route. The forward policy drops everything, even if someone (or something, like Docker) switches on ip_forward. This also keeps the host from ever becoming a bridge between the DMZ and the internal network.


7. Optional: egress filtering

A DMZ host is the most likely to be compromised. The first thing an attacker does is download tools and call home. With a default-deny output policy, a compromised web application can only reach what you allowed. It’s the single most effective control against that, and it costs some maintenance.

Replace the output chain:

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

        ct state vmap { established : accept, related : accept, invalid : drop }
        oifname "lo" accept

        # the host's own IPv6 and IPv4 basics
        meta l4proto { icmp, ipv6-icmp } accept
        udp sport 68 udp dport 67 accept                        # DHCP, if used

        # infrastructure on the internal network
        oifname $LAN_IF ip daddr 10.20.0.53 meta l4proto { tcp, udp } th dport 53 accept    # DNS
        oifname $LAN_IF ip daddr 10.20.0.30 tcp dport 3128 accept                           # proxy: apt, ACME, plugin updates
        oifname $LAN_IF ip daddr 10.20.0.25 tcp dport { 25, 587 } accept                    # mail relay
        udp dport 123 accept                                                                # NTP
        tcp dport 4460 accept                                                               # NTS key exchange

        # replies to Prometheus and SSH are "established"; nothing else needed

        limit rate 10/minute burst 20 packets log prefix "nft output drop: " level info
    }Code language: PHP (php)

Then make everything go through the proxy:

  • apt: /etc/apt/apt.conf.d/90proxy with Acquire::http::Proxy "http://10.20.0.30:3128/"; and the same for https.
  • certbot and other tools: HTTPS_PROXY=http://10.20.0.30:3128 in their unit or environment.
  • WordPress (updates, plugins): WP_PROXY_HOST and WP_PROXY_PORT in wp-config.php.

The proxy can then allowlist domains, which is far easier to maintain than IP addresses. Watch journalctl -k -g 'nft output drop' for a week after you switch. Every line is either something you forgot or something that shouldn’t be talking to the internet.

Don’t forget the services that must reach out: Fail2Ban mails, the CrowdSec agent talking to its central API, backup clients, log shipping, monitoring push. Note each one in a comment next to its rule.


8. Loading safely with automatic rollback

A wrong rule over SSH can lock you out. This script loads the new rules and puts the last good ones back automatically after 90 seconds, unless you confirm. The rollback runs as a systemd timer, so it still fires when your SSH session dies.

Create /usr/local/sbin/nft-apply:

#!/bin/bash
# nft-apply: load /etc/nftables.conf, roll back automatically unless confirmed.
#   nft-apply [seconds]   load the rules, roll back after N seconds (default 90)
#   nft-apply --confirm   keep the new rules and save them as the last good set
set -euo pipefail

CONF=/etc/nftables.conf
GOOD=/etc/nftables.conf.good

if [ "${1:-}" = "--confirm" ]; then
    systemctl stop nft-rollback.timer 2>/dev/null || true
    cp -a "$CONF" "$GOOD"
    echo "Confirmed. $GOOD updated."
    exit 0
fi

WAIT=${1:-90}

# 1. check: parses and validates against the kernel, changes nothing
nft -c -f "$CONF"

# 2. arm the rollback first
if [ -f "$GOOD" ]; then
    ROLLBACK="cp -a $CONF $CONF.rejected && cp -a $GOOD $CONF && nft -f $CONF"
else
    ROLLBACK="nft destroy table inet filter"     # first run: fall back to no table
fi
systemctl stop nft-rollback.timer 2>/dev/null || true
systemctl reset-failed nft-rollback.service 2>/dev/null || true
systemd-run --quiet --unit=nft-rollback --on-active="${WAIT}s" /bin/sh -c "$ROLLBACK"

# 3. load
nft -f "$CONF"

echo "New rules are active. Test from a NEW ssh session, then run:"
echo "    nft-apply --confirm"
echo "Otherwise the previous rules come back in ${WAIT} seconds."Code language: PHP (php)
chmod 0750 /usr/local/sbin/nft-apply
nft-apply
# open a second SSH session, test, then:
nft-apply --confirmCode language: PHP (php)

If the timer fires, your edited file is saved as /etc/nftables.conf.rejected, so you don’t lose your work.


9. Testing and debugging

Look at what’s loaded:

nft list ruleset                           # everything, all tables
nft list table inet filter                 # just yours
nft -a list chain inet filter input        # with rule handles
nft list set inet filter ssh_meter_v4      # who is currently being rate-limitedCode language: PHP (php)

Counters show which rules match. Watch them while you test:

watch -n1 'nft list chain inet filter input | grep -E "counter|drop"'
nft reset counters table inet filter       # start from zeroCode language: PHP (php)

Scan from each side. Run this from a host in the DMZ, from the admin network and from a random internal host. Each must see only what the table in section 4 allows:

nmap -Pn -p- 172.30.20.21
nmap -Pn -p- 10.20.10.21
nmap -6 -Pn -p- 2001:db8:20::21Code language: CSS (css)

Trace one packet through every chain and see which rule decides:

nft add chain inet filter trace_pre '{ type filter hook prerouting priority -350; }'
nft add rule inet filter trace_pre ip saddr 10.20.0.50 meta nftrace set 1
nft monitor trace
# ... reproduce the problem from 10.20.0.50, then Ctrl+C
systemctl reload nftables                  # removes the trace chain againCode language: PHP (php)

Conntrack shows the connections the firewall knows about:

apt install conntrack
conntrack -L | grep 'dport=443' | head
conntrack -S                               # look for "drop" and "insert_failed"Code language: PHP (php)

10. Living together with Fail2Ban and CrowdSec

Both tools manage their own tables:

ToolTableHook
Fail2Ban (banaction = nftables)inet f2b-tableinput, just before the standard filter priority
CrowdSec firewall bouncer (nftables mode)ip crowdsec, ip6 crowdsec6input (and optionally forward)

Because drop is final (section 2), their bans work no matter what your table accepts. A banned address that your input_dmz would accept is still dropped in their chain. And because this ruleset only destroys inet filter, reloading it never removes their bans.

Two rules to keep it that way:

  • Never flush ruleset, and fix Debian’s ExecStop (section 3).
  • Exporters for these tools (CrowdSec metrics on 6060, for example) are ordinary services. Allow them in input_lan from @monitor_v4 / @monitor_v6, like the node exporter.

For the Fail2Ban side, see my guide Fail2Ban with nftables on Debian 13.


11. Running Docker on the same host

Docker writes its own firewall rules. Your ruleset has to leave them alone, and it still has to let container traffic through your own forward chain. Here’s what changes.

11.1 Where Docker’s rules live

With the default backend, Docker uses iptables, which on Debian 13 is iptables-nft. Its rules appear as nftables tables: ip filter, ip nat and ip raw, and the ip6 versions when IPv6 is enabled. The chains include DOCKER-USER, DOCKER-FORWARD and DOCKER in filter, port mapping and masquerading in nat, and a raw rule that blocks direct access to container addresses from outside.

nft list tables
# table inet filter        <- yours
# table ip filter          <- Docker (iptables-nft)
# table ip nat             <- Docker
# table ip raw             <- Docker
# table ip6 filter         <- Docker, with IPv6
# table ip6 natCode language: PHP (php)

Don’t edit those tables. Docker rewrites them whenever it starts or a network changes. If they get wiped anyway (a flush ruleset, an nftables restart with the default ExecStop), rebuild them with systemctl restart docker.

11.2 Why your forward chain must allow container traffic

Docker enables IP forwarding and accepts its container traffic in its own FORWARD chain. But your inet filter forward chain hooks in at the same point, and drop is final. With the ruleset from section 5, containers can’t reach the internet and published ports don’t work. Your forward chain must accept that traffic too.

That’s not a weakness. It’s the point: your table decides, Docker’s table can only drop more.

If you applied the sysctl hardening from my Debian 13 VM hardening guide, net.ipv4.ip_forward = 0 conflicts with Docker. Docker turns forwarding on at start, and the sysctl turns it off again at the next sysctl --system. On a Docker host, remove those two lines. Your forward chain with policy drop is what keeps the host from routing between the DMZ and the internal network.

11.3 Published ports never reach your input chain

docker run -p 443:443 doesn’t open a port on the host the normal way. Docker DNATs the packet in prerouting to the container’s address. The packet is then forwarded to the bridge, so it never passes input. Your carefully written input_dmz and input_lan don’t apply to published ports.

Two consequences:

  • Filter published ports in forward, with ct status dnat.
  • After DNAT, tcp dport is the container’s port, not the one the client connected to. Use ct original proto-dst for the published port.

Better still, publish only on a specific address. Set the default in /etc/docker/daemon.json:

{
  "ip": "127.0.0.1"
}Code language: JSON / JSON with Comments (json)

Now -p 8080:80 listens on localhost only, behind a reverse proxy on the host, and your normal input rules apply to the proxy. For a port that really must be public, name the address: -p 172.30.20.21:443:443. Or use network_mode: host, which most of my Docker guides do, so the container’s ports are plain host ports filtered by input.

11.4 The forward chain for a Docker host

Replace the forward chain in /etc/nftables.conf with this, and add the two helper chains:

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

        ct state vmap { established : accept, related : accept, invalid : drop }

        iifname "docker0" jump from_docker
        iifname "br-*" jump from_docker
        oifname "docker0" jump to_docker
        oifname "br-*" jump to_docker

        limit rate 10/minute burst 20 packets log prefix "nft forward drop: " level info
    }

    # containers -> elsewhere
    chain from_docker {
        # internet, via the default route in the DMZ
        oifname $DMZ_IF accept

        # internal services the containers need, and nothing else
        oifname $LAN_IF ip daddr 10.20.0.53 meta l4proto { tcp, udp } th dport 53 accept
        oifname $LAN_IF ip daddr 10.20.0.30 tcp dport 3128 accept

        # between containers; Docker's own isolation rules still apply
        oifname "docker0" accept
        oifname "br-*" accept
    }

    # elsewhere -> containers: published ports only
    chain to_docker {
        # public ports, from the DMZ
        iifname $DMZ_IF ct status dnat meta l4proto tcp ct original proto-dst { 80, 443 } accept

        # an admin UI published on the internal leg, for admins only
        iifname $LAN_IF ct status dnat meta l4proto tcp ct original proto-dst 3000 ip saddr @admin_v4 accept
    }Code language: PHP (php)
  • docker0 is the default bridge, br-* are the user-defined networks from Compose. Your old rules may only cover one of them.
  • Replies are handled by the ct state line, so you don’t need an “external to Docker” rule for return traffic. A rule like iifname "ens192" oifname "br-*" accept accepts every new connection to every published port, not only replies.
  • Containers that should be completely offline belong on a network with internal: true in Compose. Docker blocks them itself.

Containers that talk to the host, for example to a database on the host, come in on the bridge interface and hit input. Allow exactly that, in the input chain before the interface map:

        iifname "br-*" ip saddr 172.18.0.0/16 tcp dport 5432 acceptCode language: JavaScript (javascript)

11.5 IPv6 forwarding and SLAAC

When IPv6 forwarding is on, Linux treats the host as a router and ignores Router Advertisements. If your interfaces get their IPv6 address and default route by SLAAC, they lose the route when Docker turns forwarding on. Tell the kernel to accept RAs anyway:

cat > /etc/sysctl.d/60-ipv6-ra-with-forwarding.conf <<'EOF'
net.ipv6.conf.ens192.accept_ra = 2
net.ipv6.conf.ens224.accept_ra = 2
EOF
sysctl --systemCode language: JavaScript (javascript)

With static IPv6 addresses and a static default route, you don’t need this.

11.6 Docker’s nftables backend

Docker 29 added a native nftables backend. It’s experimental, and options and behaviour may still change. You enable it in daemon.json with "firewall-backend": "nftables". The differences:

  • Docker creates the tables ip docker-bridges and ip6 docker-bridges instead of the iptables tables.
  • There is no DOCKER-USER chain. Docker’s documentation says to use your own table with base chains, which is exactly what this ruleset does.
  • Docker doesn’t enable IP forwarding itself and doesn’t add a default drop policy. Enable net.ipv4.ip_forward = 1 and net.ipv6.conf.all.forwarding = 1 yourself, and rely on your own forward chain to drop.
  • It can’t be used in Swarm mode.

Because your rules live in your own inet filter table and decide on their own, the ruleset above works unchanged with either backend. Stay on the default until the nftables backend is no longer experimental.

11.7 Checking the Docker setup

docker run --rm alpine wget -qO- https://example.org >/dev/null && echo "egress OK"
nmap -Pn -p 80,443,3000 172.30.20.21        # from the DMZ: 80/443 only
nft list chain inet filter forward          # counters on the jump rules
journalctl -k -g 'nft forward drop' --since -10mCode language: PHP (php)

12. Day-2 operations

TaskCommand
Edit and applyEdit /etc/nftables.conf, nft-apply, test, nft-apply --confirm
Allow another admin address nownft add element inet filter admin_v4 { 10.20.5.7 }, then add it to the file too
Remove itnft delete element inet filter admin_v4 { 10.20.5.7 }
Plain reloadsystemctl reload nftables (never restart)
What gets droppedjournalctl -k -g 'nft .* drop' --since today
Who is rate-limitednft list set inet filter ssh_meter_v4
Reset countersnft reset counters table inet filter
Changes to the rulesAudited with -w /etc/nftables.conf -p wa -k firewall (see the hardening guide)

Runtime changes like nft add element are lost on the next reload. The file is the source of truth. Keep /etc under version control (etckeeper), so every firewall change has a date and a diff.


13. Troubleshooting

SymptomLikely causeFix
Syntax error on the destroy table linenftables older than 1.0.8 (copied config to an old host)Use Debian 13’s nftables, or table inet filter {} followed by flush table inet filter instead
SSH from admins drops after loadingNo route back to the admin network via ens192; the reverse path filter dropsAdd the static route; check nft list chain inet filter prerouting counters
IPv6 stops working after a whileICMPv6 Neighbour Discovery or RAs blocked, or forwarding turned on with SLAACKeep the icmp_in chain as is; set accept_ra = 2 (section 11.5)
Large downloads hang, small requests workICMP “fragmentation needed” / “packet too big” droppedAllow them (they are in icmp_in); never drop all ICMP
Docker containers have no internetYour forward chain drops themSection 11.4
Docker’s rules gone after a firewall changeflush ruleset or systemctl restart nftablessystemctl restart docker; fix ExecStop (section 3)
Published Docker port open to the world although input doesn’t allow itPublished ports are forwarded, not inputFilter them in to_docker, or bind to 127.0.0.1 (section 11.3)
Fail2Ban bans disappear on reloadYour config flushes the rulesetUse destroy table inet filter only
Log full of nft input drop from broadcast addressesBroadcast/multicast reaching the log ruleKeep the meta pkttype drop before the log rule
The ruleset fails to load at boot but loads fine laterAn iif rule for an interface that doesn’t exist yet at bootUse iifname (section 6.2)

14. Checklist

  • โ˜ nftables enabled, Debian’s ExecStop no longer flushes the whole ruleset
  • โ˜ /etc/nftables.conf replaces only inet filter with destroy table, never flush ruleset
  • โ˜ Input and forward policies are drop; every interface has its own chain via the verdict map
  • โ˜ Reverse path filter active for IPv4 and IPv6, with correct routes on every interface
  • โ˜ ICMPv6 essentials and Packet Too Big allowed, ping rate-limited
  • โ˜ SSH only from the admin sets, rate-limited per source address
  • โ˜ Exporters only from Prometheus; VRRP only from the partner
  • โ˜ Logging is rate-limited, broadcast noise is dropped silently
  • โ˜ Optional: output policy drop, everything else through the proxy
  • โ˜ Changes go through nft-apply with automatic rollback
  • โ˜ Port scans from the DMZ, the admin network and another internal host show only what’s intended, for IPv4 and IPv6
  • โ˜ Fail2Ban/CrowdSec tables survive a reload
  • โ˜ Docker hosts: forward rules for docker0 and br-*, published ports filtered with ct status dnat or bound to an address, ip_forward not disabled by sysctl