Skip to content

nftables NAT and port forwarding on a Linux gateway

Configure nftables NAT and port forwarding on a Linux gateway: DNAT a public port to an internal host, masquerade outbound traffic, fix hairpin NAT, and persist it in /etc/nftables.conf.

Port forwarding on a Linux gateway is three separate things that all have to be right at once: the kernel has to be willing to route between interfaces, the nat table has to rewrite the destination address in prerouting, and the filter table’s forward chain has to actually accept the rewritten packet. Miss any one and the connection hangs with no log line to explain it. This guide builds a working nftables gateway from an empty ruleset: persistent IP forwarding, a nat table with correct hooks and priorities, a DNAT rule that forwards a public port to an internal host, masquerade for outbound traffic, the hairpin case that breaks access from your own LAN, and a named map so fifty forwards do not become fifty rules. It ends with nft monitor trace and conntrack -L, so you can prove which rule matched instead of guessing.

What you’ll accomplish

  • A Linux gateway that routes between a WAN and a LAN interface, with net.ipv4.ip_forward set persistently rather than until the next reboot.
  • A single /etc/nftables.conf holding both the filter and nat tables, loaded atomically by nftables.service at boot.
  • TCP 443 on the gateway’s public address forwarded to an internal web server, with the forward chain explicitly accepting it and ct state established,related handling the return path.
  • Hairpin NAT working, so a laptop on the LAN can reach the service by its public name without a split-horizon DNS workaround.
  • A named map driving many port forwards from one rule, and a repeatable way to trace a packet through the ruleset when something is wrong.

Prerequisites

  • A Linux host acting as a router with at least two interfaces. The examples use wan0 (public, 203.0.113.10) and lan0 (10.20.0.1/24), with the internal web server at 10.20.0.20. Substitute your own names; ip -brief addr will tell you what they are.
  • nftables 0.9.8 or newer and a kernel of 5.4 or newer. Debian 11+, Ubuntu 20.04+, AlmaLinux 9, and Rocky 9 all qualify. Check with nft --version.
  • Root or sudo, plus out-of-band console access. You are editing the firewall of a router; a typo can lock you out of SSH.
  • On Debian and Ubuntu, apt install nftables gives you the nftables.service unit and an /etc/nftables.conf that the unit loads. On RHEL-family systems the package is also nftables, but firewalld is usually installed and enabled, and firewalld owns the ruleset — see the troubleshooting section before you fight it.
  • If you are coming from an existing iptables firewall, do the conversion first: migrating from iptables to nftables covers that path, and the iptables NAT and port forwarding article is the equivalent recipe in the older syntax.

How it works

A packet arriving on wan0 destined for the gateway’s public IP passes through netfilter hooks in a fixed order. The prerouting hook fires first, before the routing decision. A chain of type nat hook prerouting priority dstnat (numeric -100) rewrites the destination address there, which means the routing decision that follows sees 10.20.0.20, not 203.0.113.10, and routes the packet out lan0 instead of delivering it locally.

Path of a DNATed packet through the netfilter prerouting, forward and postrouting hooks, showing where the destination and source addresses are rewritten

Because the packet is now being forwarded rather than delivered locally, it traverses the forward hook, not input. This is where most port forwarding attempts die: your filter table has policy drop on forward, the DNAT already happened, and the packet is silently dropped with the internal address as its destination. The rule you need in forward matches the post-DNAT address.

Finally postrouting fires, where a chain of type nat hook postrouting priority srcnat (numeric 100) can rewrite the source address. For traffic leaving the LAN toward the internet, masquerade sets the source to whatever address wan0 currently holds.

Only the first packet of a connection traverses the nat chains. Conntrack records the translation, and every subsequent packet in both directions is rewritten automatically from that entry. This is why a nat chain with a dozen rules costs almost nothing per packet, and why conntrack -L is the fastest way to see whether a translation actually got created.

Step-by-step

1. Enable IP forwarding persistently. The runtime toggle and the persistent setting are separate; set both.

sudo sysctl -w net.ipv4.ip_forward=1
echo 'net.ipv4.ip_forward = 1' | sudo tee /etc/sysctl.d/99-gateway.conf
sudo sysctl --system

Confirm the value survived:

sysctl net.ipv4.ip_forward
net.ipv4.ip_forward = 1

If you skip the file in /etc/sysctl.d/, everything below works until the next reboot and then stops, which is a memorable way to spend a morning.

2. Write the ruleset as a script, not as a pile of commands. Create /etc/nftables.conf with both tables. The leading flush ruleset makes the file authoritative, so loading it twice is safe.

sudo install -m 0600 /dev/null /etc/nftables.conf
sudo nano /etc/nftables.conf
#!/usr/sbin/nft -f

flush ruleset

define WAN = "wan0"
define LAN = "lan0"
define LANNET = 10.20.0.0/24
define WEB = 10.20.0.20

table inet filter {
  chain input {
    type filter hook input priority filter; policy drop;
    ct state established,related accept
    ct state invalid drop
    iif "lo" accept
    iifname $LAN accept
    iifname $WAN tcp dport 22 accept
    ip protocol icmp accept
  }

  chain forward {
    type filter hook forward priority filter; policy drop;
    ct state established,related accept
    ct state invalid drop
    iifname $LAN oifname $WAN accept
    iifname $WAN oifname $LAN ip daddr $WEB tcp dport { 80, 443 } accept
  }

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

table ip nat {
  chain prerouting {
    type nat hook prerouting priority dstnat; policy accept;
    tcp dport { 80, 443 } dnat to $WEB
  }

  chain postrouting {
    type nat hook postrouting priority srcnat; policy accept;
    oifname $WAN masquerade
  }
}

Two details matter. The forward rule matches ip daddr $WEB because DNAT has already rewritten the destination by the time the packet reaches that hook. And the prerouting DNAT rule deliberately has no iifname $WAN restriction, which is what makes hairpin possible in step 5.

3. Load it and check the syntax. nft parses the whole file before applying anything, so a syntax error leaves the previous ruleset intact.

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

Then apply it:

sudo nft -f /etc/nftables.conf

Silence means success. Print what the kernel actually holds:

sudo nft list table ip nat
table ip nat {
	chain prerouting {
		type nat hook prerouting priority dstnat; policy accept;
		tcp dport { 80, 443 } dnat to 10.20.0.20
	}

	chain postrouting {
		type nat hook postrouting priority srcnat; policy accept;
		oifname "wan0" masquerade
	}
}

Note that nft expanded the define variables. What you read back is the kernel’s view, not your file.

4. Enable the service so it survives a reboot. The unit simply runs nft -f /etc/nftables.conf.

sudo systemctl enable --now nftables.service
sudo systemctl is-enabled nftables.service
enabled

5. Handle the hairpin case. A laptop on the LAN resolves your public name to 203.0.113.10, sends the packet to the gateway, and DNAT rewrites the destination to 10.20.0.20. The web server then replies straight to 10.20.0.100 with a source of 10.20.0.20 — an address the laptop never contacted, so its kernel discards the reply and the connection hangs. Fix it by also masquerading LAN-to-LAN traffic that has been DNATed, which forces the reply back through the gateway:

sudo nft add rule ip nat postrouting ip saddr 10.20.0.0/24 ip daddr 10.20.0.20 tcp dport { 80, 443 } masquerade

Add the same line to the postrouting chain in /etc/nftables.conf, above or below the masquerade rule, so it persists. You also need the forward chain to permit LAN-to-LAN forwarded traffic, since the packet enters and leaves on lan0:

iifname $LAN oifname $LAN ip daddr $WEB tcp dport { 80, 443 } accept

The tradeoff is that the web server now sees the gateway’s LAN address as the client for internal requests, which will flatten your access logs for internal users. Split-horizon DNS avoids that, at the cost of a second DNS view to maintain.

6. Replace rule sprawl with a named map. Once you have more than a handful of forwards, one rule per service becomes tedious to audit. A map keyed on destination port, holding an address and port concatenation, collapses them into a single rule.

table ip nat {
  map forwards {
    type inet_service : ipv4_addr . inet_service
    elements = {
      443 : 10.20.0.20 . 443,
      2222 : 10.20.0.31 . 22,
      5432 : 10.20.0.40 . 5432
    }
  }

  chain prerouting {
    type nat hook prerouting priority dstnat; policy accept;
    iifname $WAN tcp dport vmap { 443 : jump do_forward, 2222 : jump do_forward, 5432 : jump do_forward }
  }

  chain do_forward {
    dnat ip addr . port to tcp dport map @forwards
  }
}

If you prefer to keep it to one rule, drop the verdict map and let the DNAT statement do the lookup directly — a packet whose port is not in the map simply falls through unchanged:

chain prerouting {
  type nat hook prerouting priority dstnat; policy accept;
  iifname $WAN dnat ip addr . port to tcp dport map @forwards
}

Adding a forward is then a one-liner, applied without reloading the ruleset:

sudo nft add element ip nat forwards { 8443 : 10.20.0.50 . 443 }
sudo nft list map ip nat forwards
table ip nat {
	map forwards {
		type inet_service : ipv4_addr . inet_service
		elements = { 443 : 10.20.0.20 . 443,
			     2222 : 10.20.0.31 . 22,
			     5432 : 10.20.0.40 . 5432,
			     8443 : 10.20.0.50 . 443 }
	}
}

Remember that the forward chain still has to accept each destination, so widen that rule to match the set of internal servers you are forwarding to.

Validate it works

From an external host, open the forwarded port and confirm you reach the internal service rather than the gateway:

curl -sS -o /dev/null -w '%{http_code} %{remote_ip}\n' https://203.0.113.10/
200 203.0.113.10

On the gateway, confirm conntrack recorded a translation. The presence of a dst=10.20.0.20 on the reply tuple is the proof that DNAT fired:

sudo conntrack -L -p tcp --dport 443 2>/dev/null
tcp 6 431999 ESTABLISHED src=198.51.100.7 dst=203.0.113.10 sport=51234 dport=443 src=10.20.0.20 dst=198.51.100.7 sport=443 dport=51234 [ASSURED] mark=0 use=1

Check that rules are actually being hit rather than merely present. Add counter to any rule you care about, then:

sudo nft list ruleset -a | grep -A2 'hook prerouting'

For outbound masquerade, curl from an internal host and confirm the public address is what the internet sees:

curl -sS https://api.ipify.org
203.0.113.10

Finally, verify hairpin from a LAN client using the public name:

curl -sS -o /dev/null -w '%{http_code}\n' --resolve example.com:443:203.0.113.10 https://example.com/
200

Troubleshooting

The connection hangs and nothing appears on the internal server. Check forwarding first, because it is the cheapest test: sysctl net.ipv4.ip_forward must report 1. If it does, the packet is likely being dropped in forward. Add a temporary logging rule just above the policy drop and watch the journal:

sudo nft add rule inet filter forward log prefix "fwd-drop " counter
sudo journalctl -kf

A line naming DST=10.20.0.20 confirms the DNAT worked and the filter is the problem. Remember the accept rule must match the internal address, never the public one.

DNAT works from outside but not from the LAN. This is hairpin, covered in step 5. The tell is that an external curl succeeds while an internal one hangs, and conntrack -L on the gateway shows an entry in SYN_SENT that never advances. Confirm by running tcpdump -ni lan0 host 10.20.0.20 and port 443 on the gateway: you will see the SYN go out and the SYN/ACK come back with a source of 10.20.0.20 rather than the public address. The masquerade rule from step 5 fixes it.

Rules are correct but nothing matches, and nft list ruleset shows rules you never wrote. On RHEL, AlmaLinux, and Rocky, firewalld manages nftables and will overwrite your tables on any reload. Either express the forward through firewalld, or take nftables over entirely:

sudo systemctl disable --now firewalld
sudo systemctl enable --now nftables

Do this only with console access. If you want to keep firewalld, the firewalld zones and rules article covers its own forwarding syntax, and mixing the two is a reliable source of confusion.

The wrong rule is matching, or you cannot tell which one is. Turn on tracing for the traffic you care about and watch it walk the ruleset. Restrict the trace tightly — an unrestricted trace on a busy gateway produces unusable volume.

sudo nft add table ip trace
sudo nft add chain ip trace pre '{ type filter hook prerouting priority -301; }'
sudo nft add rule ip trace pre ip saddr 198.51.100.7 tcp dport 443 meta nftrace set 1
sudo nft monitor trace
trace id 3f2a1b04 ip trace pre packet: iif "wan0" ip saddr 198.51.100.7 ip daddr 203.0.113.10 tcp dport 443
trace id 3f2a1b04 ip nat prerouting rule tcp dport { 80, 443 } dnat to 10.20.0.20 (verdict accept)
trace id 3f2a1b04 inet filter forward verdict continue

Delete the trace table when you are done: sudo nft delete table ip trace.

Connections work briefly then drop under load. The conntrack table is full and new entries are refused; dmesg will show nf_conntrack: table full, dropping packet. Raise net.netfilter.nf_conntrack_max and review timeouts — tuning Linux conntrack walks through sizing it against real connection rates rather than guessing.

When this is the wrong approach

Port forwarding on a gateway is a layer-3 tool, and it stops being the right one as soon as you need layer-7 decisions. If you are forwarding several HTTPS services and want to route by hostname, terminate TLS, or fail over between backends, a reverse proxy on the gateway does that properly and DNAT does not. If you are forwarding to more than one backend for capacity, use a load balancer with health checks — nftables can hash across a set of destinations, but it has no idea whether a backend is alive.

In a cloud environment, DNAT on a self-managed gateway usually duplicates something the platform already offers. Cloud load balancers, NAT gateways, and security groups handle the same traffic with fewer moving parts and no single host to lose. Building your own is worth it when you need protocols or behaviour the platform does not offer, not as a default.

And if the goal is remote access to internal services for staff, a VPN is a better answer than a forwarded port. Exposing a management port to the internet, even on a non-standard number, means it will be found and hammered within hours.

For the exact syntax of any statement here, the nftables NAT documentation is the authority and stays current with kernel changes.

If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.