~/notes/2026|09|05
iptables from Scratch: Part 3 | NAT and Port Forwarding
Filtering is the half of iptables everyone learns. NAT is the half that actually connects things: one public IP, a LAN of machines behind it, and the rules that make the internet come to them. This is Part 3, and it is all about rewriting addresses.
Masquerade: the whole LAN wears one IP
Your router has one public address and a dozen devices behind it. When a laptop sends a packet out, the router rewrites the source to its own public IP and remembers the mapping. That is masquerade, and it is two lines:
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
sysctl -w net.ipv4.ip_forward=1First line: in the nat table, after routing, rewrite the source on the way out. Second line: actually forward packets between interfaces, which Debian disables by default. Make it permanent:
# /etc/sysctl.d/99-forward.conf
net.ipv4.ip_forward = 1DNAT: invite the internet in, selectively
Masquerade lets you reach out. To reach in — a web server on 192.168.1.10, say — you translate the destination:
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 443 -j DNAT --to-destination 192.168.1.10:443Packets arriving on the public interface for port 443 get rewritten towards the internal server. Do not forget the matching FORWARD rule, because NAT happens before filtering and the forward chain still has the final say:
iptables -A FORWARD -i eth0 -o eth1 -p tcp --dport 443 -d 192.168.1.10 -j ACCEPTWhy you will mix up PREROUTING and POSTROUTING once
Everyone does. PREROUTING edits packets before the routing decision (incoming DNAT). POSTROUTING edits them after (outgoing masquerade). If your port forward does nothing, you put the rule in the wrong hook or forgot the FORWARD accept.
See the translation working
iptables -t nat -L -n -v
conntrack -L | head # the live NAT sessions, if conntrack is installedThe nat table listing shows your rules; conntrack shows the actual mappings in flight. When a connection "works from inside but not outside", these two commands pinpoint whether the rewrite or the forward is the problem.
NAT is where iptables stops being a filter and becomes the plumbing of your network. With filter rules from Part 2 and these NAT lines, one Linux box can be a perfectly respectable home or lab router.