Skip to content

NAT, PAT & Port Forwarding; DHCP Lease Flow; CGNAT; Hairpin NAT ​

"...which would permit multiple nodes in a local network to simultaneously access remote networks using the single IP address assigned to their router." — Srisuresh & Egevang, RFC 3022, Traditional IP Network Address Translator (Traditional NAT), 2001 (on NAPT)

Summary: NAT lets many private hosts share a few public addresses by rewriting IP addresses and ports in flight and remembering each rewrite in a table; DHCP is how those private hosts got their addresses in the first place. Focus: The translation table and conntrack, source vs destination NAT, port forwarding, hairpin, double NAT and CGNAT, NAT traversal, NAT in Docker, Kubernetes and the cloud, losing the client IP and getting it back, and the DHCP DORA exchange with leases and options. Learning goal: Predict what source address every hop sees, explain why "it works on my LAN but not from the internet" happens, read the NAT and conntrack state of a machine, and write the code and configuration that survive NAT.

This chapter is the complete reference for how a developer meets NAT and DHCP: a home router, a cloud NAT gateway, docker run -p, a Kubernetes NodePort, a carrier that shares one public IPv4 among thousands of customers. It builds on IP addressing, private ranges and CIDR (the address space NAT hides) and network models (where NAT sits in the stack). Sockets, ephemeral ports and ss live in ports, sockets and connections; DNS in DNS resolution for developers; filtering rules in firewalls; the container models in Docker networking and Kubernetes networking; tunnels and WireGuard in VPNs and tunnels; a symptom-first view in the troubleshooting playbook. Load balancers, proxies and rate limiting as design topics stay in system design: forward vs reverse proxies, load balancing, rate limiting, TCP and UDP.

Page map ​

If you are looking forGo to
The one-page tables to memoriseEverything in one minute
Why NAT exists and what it costsWhy NAT and DHCP exist
RFCs, history, NAT terminologyWhere it comes from
Static, dynamic, PAT, source vs destination NATNAT types
The translation table, conntrack, 5-tuple, timeoutsThe translation table and conntrack
How a reply finds its way backReply path
Port forwarding, docker run -pPort forwarding (DNAT)
Container cannot reach itself through the public portHairpin NAT
Double NAT, 100.64.0.0/10, why self-hosting failsDouble NAT and CGNAT
STUN, TURN, ICE, hole punching, WireGuard keepaliveNAT traversal
FTP, SIP, ALGsProtocols that embed IPs
Pods, NodePort, externalTrafficPolicy, egress IPsNAT in Kubernetes
NAT gateway, Internet gateway, Elastic IP, costNAT in the cloud
Everything is one client IP: X-Forwarded-For, PROXY protocolLost client IPs
DHCP DORA, leases, options, relay, rogue serversDHCP
DHCPv6 and SLAACDHCPv6 vs SLAAC
Static vs dynamic addresses, ephemeral portsAddressing choices
iptables, nft, conntrack, ipconfig getpacketSeeing NAT
Go code: forwarder, PROXY protocol, XFF, hole punchSolving the classic problems
Laravel: TrustProxies, rate limits, webhooksLaravel
Which design for which situationChoosing
Monolith to distributedIn architecture
Reproduce itLab
Bugs, misconceptions, cheat sheet, glossaryCommon bugs, Misconceptions, Cheat sheet, Glossary

Everything in one minute ​

The picture. Every row is unpacked later.

ThingIn plain wordsTiny exampleWhere it lives
NATA device rewrites addresses in packets as they pass192.168.1.10 becomes 203.0.113.7 on the way outRouter, firewall, cloud gateway, Docker host
PAT / NAPT / masqueradeMany private hosts share one public IP; ports tell them apartThree laptops, one public IP, ports 40000-40002Every home router
Source NAT (SNAT)Rewrite who the packet claims to be fromContainer to the internet leaves as the hostPOSTROUTING
Destination NAT (DNAT)Rewrite where the packet is goingPublic :8080 becomes 172.17.0.2:80PREROUTING / OUTPUT
Port forwardA permanent DNAT rule so the outside can reach one inside serviceRouter: WAN :443 goes to 192.168.1.10:443Router UI, docker run -p
conntrackThe kernel's table of flows that makes NAT reversibleOne row per connection, both directionsLinux netfilter
Hairpin NATAn inside client using the outside address of an inside serverLaptop opens http://203.0.113.7:8080 which is its own LAN serverRouter, Docker bridge
CGNATThe ISP does NAT for you on top of yoursWAN address 100.64.12.9, not a public IPISP
DHCPA server hands out address, gateway, DNS for a limited timeLaptop joins Wi-Fi, gets 10.84.50.174 for an hourRouter, cloud, dnsmasq

The four DHCP messages and the three timers.

Message / timerDirectionWhat it carriesWhen
DISCOVERclient to broadcast"I need an address", parameter request listBoot, link up
OFFERserver to clientyiaddr, lease time, optionsAnswer to DISCOVER
REQUESTclient to broadcastChosen address and server identifierAccepts one offer; renews at T1/T2
ACKserver to clientFinal lease and optionsLease starts
T1 (renewal)client to the same server (unicast)REQUEST50% of the lease by default
T2 (rebinding)client to any server (broadcast)REQUEST87.5% of the lease by default
Lease expiryclientMust stop using the address100%

The three things to do.

SituationDo this
Your app logs or rate-limits by client IP behind a load balancer or NATConfigure TrustProxies (Laravel) or a trusted-proxy resolver (Go) and read the rightmost untrusted hop, never the leftmost
You must be reachable from the internetPublic IP plus a port forward, or an outbound tunnel (cloudflared, ngrok, WireGuard to a VPS) when you are behind CGNAT
A hard-coded private IP keeps breakingUse DNS names, or a DHCP reservation, or a static address outside the DHCP pool

Why NAT and DHCP exist ​

IPv4 has 2^32 addresses, about 4.3 billion. The internet outgrew that. RFC 3022 describes the first remedy in its own words: many users have "multiple Network nodes in their office" but "a single IP address assigned to their remote access router", and NAPT lets them all use it. NAT turned "one address per device" into "one address per household or per company", which is why IPv4 is still alive. IPv6 (128-bit) removes the shortage, but both worlds will coexist for years, so every developer meets NAT daily.

DHCP exists for a neighbouring reason: if every device behind that router needed a hand-typed address, gateway and DNS, nothing would work out of the box. The router runs a DHCP server so a laptop joining Wi-Fi gets a working configuration with no typing.

Without itWith it
One public IPv4 per deviceOne public IPv4 per site; private addresses inside
Every host typed its own IP, mask, gateway, DNSA server hands out configuration for a limited lease
Anything on the internet can open a connection to any hostHosts behind NAT are unreachable until you forward a port (a side effect, not a firewall)
End-to-end addressing: the sender's IP is the real senderThe IP you see may be a shared gateway; the real client is hidden

The everyday picture. A company switchboard. Employees have internal extensions (private IPs). Outside callers see one phone number (public IP). When an employee calls out, the switchboard remembers "extension 12 is on line 3". When line 3 rings back, it connects to extension 12. If a stranger calls the main number and asks for extension 12, the switchboard has no idea what line to use unless you configured a rule ("calls to the main number's option 2 go to extension 12": a port forward). DHCP is the reception desk handing a new employee an extension for the day.

Three misunderstandings, up front.

MisunderstandingReality
"NAT is a firewall"NAT blocks unsolicited inbound packets only because no table row exists. It is a side effect, easily bypassed (hole punching, UPnP, a forward) and says nothing about outbound. Use a real firewall
"My server's IP is what clients see"Behind NAT, clients see the gateway's address; your server sees the gateway or load balancer's address, not the client's
"A port forward is enough to host from home"Not if your ISP uses CGNAT: the packet never reaches your router

Where it comes from ​

SourceWhat it gave us
RFC 1918 (1996)The private ranges 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 that are never routed on the internet
RFC 2663 (1999)The vocabulary: address realm, NAT, NAPT, ALG, "transparent routing"
RFC 3022 (2001)Traditional NAT: Basic NAT and NAPT (the one with ports), the table and the checksum updates
RFC 3027 (2001)"Protocol Complications with the IP Network Address Translator": why FTP and others break
RFC 4787 (2007)NAT behaviour for UDP: mapping types, filtering, hairpinning, the 2 minute UDP timer
RFC 5382 (2008)The same for TCP: the "established connection idle-timeout" must be at least 2 hours 4 minutes
RFC 6598 (2012)100.64.0.0/10, "Shared Address Space" for Carrier-Grade NAT
RFC 8445 / 8489 / 8656ICE, STUN and TURN: how WebRTC and games cross NATs
RFC 2131 / 2132 (1997)DHCP and its options; RFC 3046 relay agent information; RFC 8415 DHCPv6; RFC 4862 SLAAC
HAProxy PROXY protocol specThe de facto way a TCP proxy hands the real client address to the next hop

RFC 3022 itself says the cost plainly: the approach has "the disadvantage of taking away the end-to-end significance of an IP address, and making up for it with increased state in the network", and RFC 6598 is explicit that Shared Address Space "is distinct from RFC 1918 private address space because it is intended for use on Service Provider networks".

The concept catalogue ​

Static (1:1) NAT Good to know ​

In plain words: One private address is permanently mapped to one public address, both directions, no ports involved.

Common misunderstanding: "1:1 NAT saves addresses." It does not; it spends one public IP per private host. It exists for reachability and renumbering, not for saving addresses.

Definition: Basic NAT in RFC 3022: only the IP address is rewritten, the transport ports are untouched. The AWS Internet gateway does exactly this: it "logically provides the one-to-one NAT on behalf of your instance", so the instance only knows its private address while the internet sees its public or Elastic IP.

Outbound  10.0.1.25:44000 -> 93.184.216.34:443    becomes   54.0.0.9:44000 -> 93.184.216.34:443
Inbound   93.184.216.34:443 -> 54.0.0.9:44000      becomes   93.184.216.34:443 -> 10.0.1.25:44000

Real scenarios: an EC2 instance with a public IPv4; a DMZ server mapped to a published address; merging two companies that both used 10.0.0.0/8 (1:1 NAT hides one side behind a translated range).

ProductHow you do 1:1 NAT
Linuxiptables -t nat -A PREROUTING -d 54.0.0.9 -j DNAT --to 10.0.1.25 plus -A POSTROUTING -s 10.0.1.25 -j SNAT --to 54.0.0.9, or nft dnat to / snat to
AWSInternet gateway plus public IPv4 or Elastic IP on the instance
Home router"DMZ host" (forwards everything to one device)
Cisco IOSip nat inside source static

Dynamic NAT Good to know ​

In plain words: A pool of public addresses is handed out to private hosts as they need one and taken back when idle.

Common misunderstanding: "Dynamic NAT is what my home router does." Your router does PAT, which shares one address by port. Dynamic NAT uses one public address per active host, so it runs out when the pool is smaller than the number of active hosts.

Definition: Basic NAT with a pool; entries are created on first outbound packet and removed on timeout. Rare today because it needs many public addresses; seen in corporate edge devices with a small public block.

pool 203.0.113.10-12
t0  10.0.0.5  -> internet : takes 203.0.113.10
t1  10.0.0.6  -> internet : takes 203.0.113.11
t2  10.0.0.7  -> internet : takes 203.0.113.12
t3  10.0.0.8  -> internet : no free address, packet dropped

PAT / NAPT / masquerade Must-know ​

In plain words: Many private hosts share ONE public IP. The router also rewrites the source port so it can tell the flows apart.

Common misunderstanding: "My port 51000 stays 51000 on the internet." It may not: if two hosts use the same source port, the router changes one of them. The outside world only ever sees the router's port.

Definition: NAPT (Network Address Port Translation) in RFC 3022; "PAT" is Cisco's name; "masquerade" is Linux's flavour of SNAT that takes the outgoing interface's current address (so it keeps working when a DHCP-assigned WAN address changes).

Private LANlaptop 192.168.1.10phone 192.168.1.11tv 192.168.1.12NAT router: translation table (public IP 203.0.113.7)proto private ip:port public port remotetcp 192.168.1.10:51000 40000 93.184.216.34:443udp 192.168.1.11:51000 40001 198.51.100.5:3478tcp 192.168.1.12:49152 40002 93.184.216.34:443idle entries expire (UDP about 30 s, established TCP up to 5 days)a packet with no matching row is droppedInternet93.184.216.34:443sees 203.0.113.7:40000198.51.100.5:3478sees 203.0.113.7:40001Solid: rewrite source ip:port, create the row. Dashed: find the row by public port, rewrite the destination.about 64k ports per public IP and protocol is the hard ceiling

The diagram shows the table as the router sees it. A runnable toy version follows; its output is real.

go
// A toy PAT (NAPT) table: the heart of every home router and NAT gateway.
// It maps (private IP, private port, protocol) to a public port, expires idle
// entries, and runs out of ports exactly like a real conntrack/NAT table.
package main

import (
	"errors"
	"fmt"
	"time"
)

type Key struct {
	Proto   string
	SrcIP   string
	SrcPort uint16
	DstIP   string // part of the 5-tuple: same private socket to a different server can reuse a port
	DstPort uint16
}

type Entry struct {
	PublicPort uint16
	LastSeen   time.Time
}

type PAT struct {
	PublicIP string
	Timeout  time.Duration
	lo, hi   uint16
	table    map[Key]*Entry
	inUse    map[uint16]Key
	next     uint16
	now      func() time.Time
}

var ErrExhausted = errors.New("no free public port: table exhausted")

func NewPAT(publicIP string, lo, hi uint16, timeout time.Duration, now func() time.Time) *PAT {
	return &PAT{PublicIP: publicIP, Timeout: timeout, lo: lo, hi: hi, next: lo,
		table: map[Key]*Entry{}, inUse: map[uint16]Key{}, now: now}
}

// Outbound translates a packet leaving the private network (source NAT).
func (p *PAT) Outbound(k Key) (string, uint16, error) {
	p.expire()
	if e, ok := p.table[k]; ok {
		e.LastSeen = p.now()
		return p.PublicIP, e.PublicPort, nil
	}
	for i := 0; i <= int(p.hi-p.lo); i++ {
		port := p.lo + uint16((int(p.next-p.lo)+i)%(int(p.hi-p.lo)+1))
		if _, taken := p.inUse[port]; taken {
			continue
		}
		p.table[k] = &Entry{PublicPort: port, LastSeen: p.now()}
		p.inUse[port] = k
		p.next = port + 1
		return p.PublicIP, port, nil
	}
	return "", 0, ErrExhausted
}

// Inbound finds the private socket for a reply. No entry means the packet is
// dropped: that is why an unsolicited packet from the internet never gets in.
func (p *PAT) Inbound(proto, remoteIP string, remotePort, publicPort uint16) (Key, bool) {
	p.expire()
	k, ok := p.inUse[publicPort]
	if !ok || k.Proto != proto || k.DstIP != remoteIP || k.DstPort != remotePort {
		return Key{}, false
	}
	p.table[k].LastSeen = p.now()
	return k, true
}

func (p *PAT) expire() {
	for k, e := range p.table {
		if p.now().Sub(e.LastSeen) > p.Timeout {
			delete(p.inUse, e.PublicPort)
			delete(p.table, k)
		}
	}
}

func main() {
	clock := time.Unix(0, 0)
	now := func() time.Time { return clock }
	nat := NewPAT("203.0.113.7", 40000, 40002, 30*time.Second, now) // tiny range on purpose

	a := Key{"udp", "192.168.1.10", 51000, "198.51.100.5", 3478}
	b := Key{"udp", "192.168.1.11", 51000, "198.51.100.5", 3478} // same private port, other host
	c := Key{"tcp", "192.168.1.12", 49152, "93.184.216.34", 443}

	for _, k := range []Key{a, b, c} {
		ip, port, err := nat.Outbound(k)
		fmt.Printf("OUT %-3s %s:%d -> %s:%d   mapped to %s:%d err=%v\n", k.Proto, k.SrcIP, k.SrcPort, k.DstIP, k.DstPort, ip, port, err)
	}
	_, _, err := nat.Outbound(Key{"tcp", "192.168.1.13", 50000, "93.184.216.34", 443})
	fmt.Println("4th flow with 3 ports:", err)

	if k, ok := nat.Inbound("udp", "198.51.100.5", 3478, 40001); ok {
		fmt.Printf("IN  reply to :40001 delivered to %s:%d\n", k.SrcIP, k.SrcPort)
	}
	_, ok := nat.Inbound("udp", "203.0.113.99", 9999, 40001)
	fmt.Println("IN  unsolicited packet from another host delivered:", ok)

	clock = clock.Add(31 * time.Second) // idle timeout passes
	_, ok = nat.Inbound("udp", "198.51.100.5", 3478, 40001)
	fmt.Println("IN  reply after idle timeout delivered:", ok)
	ip, port, err := nat.Outbound(Key{"tcp", "192.168.1.13", 50000, "93.184.216.34", 443})
	fmt.Printf("4th flow after expiry: %s:%d err=%v\n", ip, port, err)
}
OUT udp 192.168.1.10:51000 -> 198.51.100.5:3478   mapped to 203.0.113.7:40000 err=<nil>
OUT udp 192.168.1.11:51000 -> 198.51.100.5:3478   mapped to 203.0.113.7:40001 err=<nil>
OUT tcp 192.168.1.12:49152 -> 93.184.216.34:443   mapped to 203.0.113.7:40002 err=<nil>
4th flow with 3 ports: no free public port: table exhausted
IN  reply to :40001 delivered to 192.168.1.11:51000
IN  unsolicited packet from another host delivered: false
IN  reply after idle timeout delivered: false
4th flow after expiry: 203.0.113.7:40000 err=<nil>
ProductFlavourCommand or setting
Linux netfilterMASQUERADEiptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
Linux netfilterSNAT --to-sourceSame, with a fixed address: faster, for static WAN IPs
nftablesmasquerade / snat tonft add rule ip nat postrouting oifname "eth0" masquerade
Cisco IOSPATip nat inside source list 1 interface Gi0/0 overload
pfSense / OPNsense / OpenBSD pfOutbound NATnat on em0 from 192.168.1.0/24 to any -> (em0) in pf
macOSInternet Sharinguses pf NAT under the hood
AWSNAT gatewaymanaged, fixed Elastic IP
DockerMASQUERADE for each bridge subnetwritten automatically

Source NAT vs destination NAT Must-know ​

In plain words: SNAT changes who a packet says it is from. DNAT changes where it says it is going. Which one you need depends on who starts the conversation.

Common misunderstanding: "NAT only rewrites the source." Outbound access for many hosts is SNAT, but every port forward, every load balancer VIP and every Kubernetes Service is DNAT.

Definition: netfilter does SNAT in POSTROUTING (the packet is already routed, "anything else on the Linux box itself ... will see the packet unchanged", as the netfilter NAT HOWTO puts it) and DNAT in PREROUTING (for traffic arriving from outside) and OUTPUT (for locally generated traffic). Masquerading is "a specialized case of Source NAT ... only be used for dynamically-assigned IP addresses".

Who starts it?        Rewrite              Chain          Example
inside -> outside     source (SNAT/masq)   POSTROUTING    laptop browses the web
outside -> inside     destination (DNAT)   PREROUTING     port forward, LB VIP
local process -> VIP  destination (DNAT)   OUTPUT         curl localhost:8080 on a Docker host
DirectionNetfilter hookiptables syntaxnftables syntax
SNATpostrouting-t nat -A POSTROUTING -o eth0 -j SNAT --to-source 203.0.113.7snat to 203.0.113.7
Masqueradepostrouting-t nat -A POSTROUTING -o eth0 -j MASQUERADEmasquerade
DNATprerouting-t nat -A PREROUTING -p tcp --dport 8080 -j DNAT --to-destination 172.17.0.2:80tcp dport 8080 dnat to 172.17.0.2:80
REDIRECTprerouting-j REDIRECT --to-ports 3128 (DNAT to the local box)redirect to :3128

The translation table and conntrack Must-know ​

In plain words: The router keeps a notebook of every conversation it has rewritten, so it can undo the rewrite on the answer. On Linux that notebook is the kernel's connection tracking table, conntrack.

Common misunderstanding: "conntrack is part of the firewall only." It is the state that makes NAT possible at all; the stateful firewall rule ESTABLISHED,RELATED is just a consumer of the same table.

Definition: A conntrack entry is keyed by the 5-tuple (protocol, source IP, source port, destination IP, destination port) of the original direction and stores the expected reply tuple, with the NAT rewrite included. Each entry has a timeout that depends on protocol state and is refreshed by traffic. When the table is full, new connections are dropped.

Real output from the lab (Docker Desktop's Linux VM), a curl to a published port:

tcp      6 431998 ESTABLISHED src=127.0.0.1 dst=127.0.0.1 sport=56997 dport=8080 src=172.17.0.2 dst=172.17.0.1 sport=80 dport=56997 [ASSURED] mark=0 use=1
tcp      6 119 TIME_WAIT src=127.0.0.1 dst=127.0.0.1 sport=59364 dport=8080 src=172.17.0.2 dst=172.17.0.1 sport=80 dport=59364 [ASSURED] mark=0 use=1

Read each line left to right. After tcp 6 (protocol number 6) comes the remaining timeout in seconds, then the state, then two tuples. The first src= dst= sport= dport= is the ORIGINAL direction (what the client sent). The second is the REPLY direction, the one the kernel will expect, with the rewrite already applied: here the reply comes from 172.17.0.2:80. 431998 seconds is nf_conntrack_tcp_timeout_established (432000, 5 days); 119 of 120 is nf_conntrack_tcp_timeout_time_wait.

Knob (sysctl net.netfilter.)DefaultMeaning
nf_conntrack_maxnf_conntrack_buckets x 4 (262144 on the lab VM)Table size; when full the kernel logs nf_conntrack: table full, dropping packet
nf_conntrack_count (read only)currentEntries now
nf_conntrack_tcp_timeout_established432000 (5 days)Idle established TCP flow
nf_conntrack_tcp_timeout_time_wait120TIME_WAIT flow
nf_conntrack_tcp_timeout_fin_wait120Closing
nf_conntrack_udp_timeout30UDP flow with traffic in one direction only
nf_conntrack_udp_timeout_stream120UDP "stream" (traffic both ways)
nf_conntrack_bucketsautoHash table size; raise together with max

RFC 4787 REQ-5 says a NAT's UDP mapping timer "MUST NOT expire in less than two minutes" (with an exception for well-known ports), and RFC 5382 REQ-5 says an established TCP idle timeout "MUST NOT be less than 2 hours 4 minutes". Real devices are looser: many consumer routers expire UDP in 30 to 60 seconds, which is why you need keepalives.

conntrack tuple (what a row stores)
  original:  proto=tcp  src=192.168.1.10:51000  dst=93.184.216.34:443
  reply:     proto=tcp  src=93.184.216.34:443   dst=203.0.113.7:40000      <- rewritten destination
  state:     ESTABLISHED   timeout: 431998 s   [ASSURED]

Table exhaustion. Every connection, including each short-lived health check and each TIME_WAIT, holds a row. A busy NAT box, a Kubernetes node or a Docker host running a scraper can fill the table; then new flows silently disappear (the SYN is dropped, the client sees a timeout, not a refusal). Check conntrack -C against nf_conntrack_max, look at conntrack -S (insert_failed, drop, early_drop) and fix by raising nf_conntrack_max, lowering timeouts for noisy protocols, reusing connections (keep-alive, pooling) or moving offending traffic to NOTRACK / raw table rules.

How a reply finds its way back Must-know ​

In plain words: The reply is addressed to the router's public IP and port. The router looks that pair up in its table, finds the private host that owns it, rewrites the destination and forwards.

Common misunderstanding: "The server knows where the client really lives." It only knows the router's address and the translated port. If the table row is gone (timeout, reboot) the reply is dropped and the client's connection hangs.

1  laptop 192.168.1.10:51000 -> web 93.184.216.34:443       SYN
2  router rewrites source -> 203.0.113.7:40000, creates row
3  web 93.184.216.34:443 -> 203.0.113.7:40000               SYN-ACK
4  router matches public port 40000 -> 192.168.1.10:51000, rewrites destination
5  laptop receives 93.184.216.34:443 -> 192.168.1.10:51000
6  IP and TCP checksums are recomputed at every rewrite

Because the address is part of the TCP/UDP checksum (the pseudo header), every NAT rewrite must also update the IP header checksum and the transport checksum. NAT is also why a TCP connection cannot survive a change of the client's public address (a phone moving from Wi-Fi to mobile data): the 4-tuple changes, so it is a new connection. QUIC adds a connection ID to survive exactly that.

Port forwarding (DNAT) Must-know ​

In plain words: A standing rule at the edge: "anything arriving at public port X goes to this inside machine, port Y". It is how an inside service becomes reachable from outside.

Common misunderstanding: "-p 8080:80 just opens a port." It installs a DNAT rule, a masquerade rule and a forwarding allowance, and in many setups starts a user-space proxy as well. The container never listens on 8080.

Definition: DNAT in PREROUTING rewrites the destination; conntrack remembers the rewrite so the reply is automatically un-NATed.

Client198.51.100.23:54321Router / Docker host (netfilter + conntrack)PREROUTINGDNAT 203.0.113.7:8080FORWARDallow dport 80conntrack entry (one row, both directions)orig 198.51.100.23:54321 -> 203.0.113.7:8080reply 172.17.0.2:80 -> 198.51.100.23:54321POSTROUTING: reply un-DNAT'ed automatically,source rewritten back to 203.0.113.7:8080Backend172.17.0.2:8012341 SYN to public ip:8080. 2 destination rewritten to 172.17.0.2:80. 3 backend replies to the client.4 conntrack reverses the rewrite. Neither side learns the other's real address.

Real rules Docker wrote for docker run -d -p 8080:80 nginx:alpine (the lab):

$ iptables -t nat -S
-A PREROUTING -m addrtype --dst-type LOCAL -j DOCKER
-A OUTPUT -m addrtype --dst-type LOCAL -j DOCKER
-A POSTROUTING -s 172.17.0.0/16 ! -o docker0 -j MASQUERADE
-A POSTROUTING -s 172.17.0.2/32 -d 172.17.0.2/32 -p tcp -m tcp --dport 80 -j MASQUERADE
-A DOCKER -p tcp -m tcp --dport 8080 -j DNAT --to-destination 172.17.0.2:80

Line by line: PREROUTING and OUTPUT send any packet addressed to a local IP into the DOCKER chain; the DOCKER chain DNATs :8080 to the container; POSTROUTING ... ! -o docker0 -j MASQUERADE is the outbound masquerade for the whole 172.17.0.0/16 bridge; the /32 to /32 rule is the hairpin helper (see Hairpin NAT). A matching FORWARD chain rule accepts tcp dport 80 to 172.17.0.2. The Docker docs state that the rules exist "to implement functionality including port publishing, and NAT/masquerading" and that "you should not modify the rules created by Docker".

WhereHow the forward is configuredReachable from
Home routerWeb UI: "Port forwarding" / "Virtual server": WAN port, LAN IP, LAN port, protocolInternet, if you have a real public IP
UPnP / NAT-PMP / PCPThe app asks the router to open a port by itself (games, torrents)Internet; a security risk if enabled blindly
Linuxiptables -t nat -A PREROUTING ... -j DNAT plus a FORWARD accept; net.ipv4.ip_forward=1Whoever can reach this host
Docker-p host:container, -p 127.0.0.1:8080:80 (loopback only), -p 8080:80/udpAll interfaces unless you bind an IP
KubernetesNodePort, LoadBalancer, hostPortNode IP:30000-32767, or the cloud LB
AWSSecurity group + route to Internet gateway + public IP; NLB/ALB listenersInternet
SSHssh -L 8080:10.0.0.5:80 bastion is a user-space forward, not NATYour laptop only

Timeline of a single request through Docker's forward (real addresses from the lab, client 192.168.65.1 is the Docker Desktop gateway):

1  client 192.168.65.1:53895 -> host 192.168.65.3:8080         SYN arrives
2  nat/PREROUTING -> DOCKER: dport 8080 -> DNAT 172.17.0.2:80
3  filter/FORWARD: DOCKER chain allows dport 80 to 172.17.0.2
4  nginx 172.17.0.2:80 sees client 192.168.65.1 (not the real remote host if it came via the userland proxy)
5  reply 172.17.0.2:80 -> 192.168.65.1:53895 matches conntrack, source rewritten to 192.168.65.3:8080

The Docker daemon can also run docker-proxy, a user-space TCP forwarder, for traffic that cannot be DNATed (loopback 127.0.0.1:8080 on a Linux host, or Docker Desktop). That is why the application inside the container often logs the bridge gateway (172.17.0.1) as the client instead of the real address, which is the next section's problem.

Hairpin NAT (NAT loopback) Important ​

In plain words: An inside machine reaches an inside server by its OUTSIDE address. The router must turn the packet around and send it back in, and also fix the source address so the reply comes back through the router.

Common misunderstanding: "If the port forward works from the internet it works from my own LAN." Many routers do not support hairpinning, so http://203.0.113.7:8080 times out from inside but works from a phone on mobile data.

Definition: RFC 4787 section 6: if two hosts X1 and X2 are behind the same NAT, "If X1 sends traffic to X2':x2', it goes to the NAT, which must relay the traffic from X1 to X2. This is referred to as hairpinning". Doing it right needs DNAT of the destination and SNAT of the source, otherwise the server answers X1 directly with its own source address and X1 drops the packet as a reply from an unknown peer.

Your server192.168.1.10Home router NATLAN 192.168.1.1WAN 100.64.12.9ISP CGNATshared pool 100.64.0.0/10public 203.0.113.7 (shared)Internetvisitorinbound SYNno table row: droppedPort forward on the home router is useless: the packet never reaches it.LAN client192.168.1.20Router, hairpin NATDNAT 203.0.113.7:8080 -> .10:80+ SNAT so the reply returns hereServer192.168.1.10:80to public ipto private ipWithout the SNAT half the server replies straight to the client and the client drops it.

The same thing happens in Docker. A container that connects to the host's published port (http://172.17.0.1:8080 or the host's LAN IP) is DNATed back to itself. I reproduced it in the lab by deleting the helper rule Docker had added:

$ iptables -t nat -D POSTROUTING -s 172.17.0.2/32 -d 172.17.0.2/32 -p tcp -m tcp --dport 80 -j MASQUERADE
$ docker exec natlab curl -s -m 4 -o /dev/null -w "self via gw:8080 -> %{http_code}\n" http://172.17.0.1:8080/
self via gw:8080 -> 000        # curl exit code 28: timeout
$ iptables -t nat -A POSTROUTING -s 172.17.0.2/32 -d 172.17.0.2/32 -p tcp -m tcp --dport 80 -j MASQUERADE
$ docker exec natlab curl ... http://172.17.0.1:8080/
after restore -> 200
Broken hairpin (no SNAT half)
1  container 172.17.0.2:35000 -> 172.17.0.1:8080
2  DNAT dest -> 172.17.0.2:80                 (source still 172.17.0.2)
3  packet loops back into the same container, source = destination host
4  container answers 172.17.0.2:80 -> 172.17.0.2:35000 (to itself, never leaves)
5  client socket waits for a SYN-ACK from 172.17.0.1:8080: sees none -> timeout

Fixed hairpin (Docker's rule, or router "NAT loopback")
2' SNAT source -> 172.17.0.1 (masquerade) so the reply must return via the gateway
ProductHairpin behaviour
Docker bridgeAdds a /32 -> /32 MASQUERADE rule per published port (above); docker-proxy also serves it
Home routers"NAT loopback" or "NAT reflection" setting; many cheap ones lack it
pfSense / OPNsense"NAT reflection mode" (pure NAT / NAT + proxy)
Linux routerDNAT in PREROUTING plus -s lan -d server -j MASQUERADE in POSTROUTING
AWSNot a gateway feature: use private DNS or the private IP from inside the VPC (split-horizon)
KubernetesServices work from their own pods thanks to kube-proxy plus hairpinMode in the CNI bridge (hairpin_mode on the veth)

The cleanest fix is never to need it: use split-horizon DNS (internal name resolves to the private IP, external name to the public IP), or use the private address or service name from inside.

Double NAT and CGNAT Must-know ​

In plain words: Double NAT is two routers in series (an ISP box plus your own). CGNAT (Carrier-Grade NAT) is the ISP doing the sharing: many customers share a public IPv4 and your router's WAN address is not public at all.

Common misunderstanding: "I forwarded the port, so people can reach my home server." If your router's WAN address is 100.64.0.0/10 or any private range, the forward is on the wrong device; the carrier's NAT has no row for the visitor's packet and drops it. Port forwards only work if your router owns the public IP.

Definition: RFC 6598 reserved 100.64.0.0/10 (100.64.0.0 to 100.127.255.255) as Shared Address Space "to accommodate the needs of Carrier-Grade NAT (CGN) devices", used "to number the interfaces that connect CGN devices to Customer Premises Equipment". Test your router's WAN IP: in 10/8, 172.16/12, 192.168/16 or 100.64/10 means you are behind at least one more NAT.

internet visitor -> 203.0.113.7:443            (shared public IP of the ISP)
ISP CGNAT: no row for this flow, no rule for this port -> drop
        ... your home router's WAN 100.64.12.9 never even sees the SYN
SituationSymptomFix
Your own router behind an ISP router (double NAT)Port forward on the inner router failsPut the ISP box in bridge mode, or forward on both, or set the inner router as the ISP box's "DMZ host"
ISP CGNAT, IPv4 onlyCannot host anything; WAN IP is 100.64/10Ask for a public IP (often paid), use IPv6, or use an outbound tunnel (cloudflared, ngrok, WireGuard to a VPS with a public IP, Tailscale)
Many users behind one CGNAT addressSites rate-limit or block "your" IP because of a neighbourPrefer IPv6; do not treat one IPv4 as one person
Games and P2P"Strict NAT" type; no direct connectionsUPnP does not help (it only talks to your router); IPv6 or relays
Rate limiting your own serviceOne public IPv4 may be thousands of real usersKey limits on user/session and use generous per-IP caps

Self-hosting behind CGNAT fails for a simple reason: inbound traffic needs an inbound mapping, mappings are created by outbound packets or by rules on the device that owns the public address, and you do not own it. The reverse-connection tunnels (see NAT traversal and Laravel) work because YOUR machine dials out, which the CGNAT happily maps.

NAT traversal: STUN, TURN, ICE, hole punching and keepalive Important ​

In plain words: Two peers behind two NATs both only talk outward. A helper server on the public internet tells each one how the other looks from the outside; then both send at the same time, which makes each NAT create the row that lets the other's packet in. If that fails, a relay carries the traffic.

Common misunderstanding: "NAT traversal means breaking through the firewall." It is the opposite: it cooperates with the NAT by sending outbound packets the NAT will map. A NAT that gives each destination a different external port (symmetric NAT) defeats it, and then a relay is the only option.

Definition: STUN (Session Traversal Utilities for NAT, RFC 8489) lets a client learn its public ip:port, the "server-reflexive address"; TURN (Traversal Using Relays around NAT, RFC 8656) allocates a relayed address on a public server; ICE (Interactive Connectivity Establishment, RFC 8445) gathers all candidates (host, server-reflexive, relayed), pairs them, runs connectivity checks and picks the best. RFC 8445's abstract: "This document describes a protocol for Network Address Translator (NAT) traversal for UDP-based communication".

Hole punching (UDP)
1  A (192.168.1.10) -> rendezvous S: REGISTER      NAT-A maps A:51000 -> 203.0.113.7:40000
2  B (10.0.0.4)     -> rendezvous S: REGISTER      NAT-B maps B:51000 -> 198.51.100.9:61000
3  S -> A: "peer is 198.51.100.9:61000"    S -> B: "peer is 203.0.113.7:40000"
4  A -> 198.51.100.9:61000   (NAT-A row now allows replies from that remote)
   B -> 203.0.113.7:40000    (NAT-B row likewise); first packets may be dropped, later ones pass
5  Both now exchange packets directly. A keepalive every 15-25 s keeps both rows alive

NAT mapping and filtering behaviour decides whether this works (RFC 4787 vocabulary): endpoint-independent mapping reuses the same external port for all destinations (needed for traversal, REQ-1: "A NAT MUST have an 'Endpoint-Independent Mapping' behavior"); address-dependent and address-and-port-dependent mapping change the external port per destination, so the port S saw is useless to the peer.

NAT type (informal name)MappingWho can send inHole punching
Full coneEndpoint-independentAnyone, once mappedEasy
Restricted coneEndpoint-independentOnly hosts the inside host sent toWorks
Port-restricted coneEndpoint-independentOnly host:port sent toWorks with simultaneous send
SymmetricAddress-and-port-dependentOnly the exact host:portUsually fails; use TURN

A STUN message is tiny and exactly 20 bytes of header for a Binding Request. The snippet builds one and decodes the XOR-MAPPED-ADDRESS answer (the address is XORed with the magic cookie 0x2112A442 so that ALGs that rewrite IPs in payloads do not mangle it):

go
// A STUN Binding Request and its XOR-MAPPED-ADDRESS answer (RFC 8489):
// how a WebRTC client learns its public ip:port as the NAT sees it.
package main

import (
	"crypto/rand"
	"encoding/binary"
	"encoding/hex"
	"fmt"
	"net/netip"
)

const magic = 0x2112A442

func bindingRequest() []byte {
	b := make([]byte, 20)
	binary.BigEndian.PutUint16(b[0:], 0x0001) // Binding Request
	binary.BigEndian.PutUint16(b[2:], 0)      // message length (no attributes)
	binary.BigEndian.PutUint32(b[4:], magic)
	rand.Read(b[8:]) // 96-bit transaction id
	return b
}

// encodeXorMapped builds the success response attribute for ip:port.
func encodeXorMapped(ap netip.AddrPort) []byte {
	a := make([]byte, 12)
	binary.BigEndian.PutUint16(a[0:], 0x0020) // XOR-MAPPED-ADDRESS
	binary.BigEndian.PutUint16(a[2:], 8)
	a[5] = 0x01 // IPv4
	binary.BigEndian.PutUint16(a[6:], ap.Port()^uint16(magic>>16))
	ip := ap.Addr().As4()
	binary.BigEndian.PutUint32(a[8:], binary.BigEndian.Uint32(ip[:])^magic)
	return a
}

func decodeXorMapped(a []byte) netip.AddrPort {
	port := binary.BigEndian.Uint16(a[6:]) ^ uint16(magic>>16)
	x := binary.BigEndian.Uint32(a[8:]) ^ magic
	var ip [4]byte
	binary.BigEndian.PutUint32(ip[:], x)
	return netip.AddrPortFrom(netip.AddrFrom4(ip), port)
}

func main() {
	req := bindingRequest()
	fmt.Printf("Binding Request (%d bytes):\n%s", len(req), hex.Dump(req))
	seen := netip.MustParseAddrPort("203.0.113.7:61234") // what the NAT made of our source
	attr := encodeXorMapped(seen)
	fmt.Printf("XOR-MAPPED-ADDRESS attribute:\n%s", hex.Dump(attr))
	fmt.Println("decoded back:", decodeXorMapped(attr))
}
Binding Request (20 bytes):
00000000  00 01 00 00 21 12 a4 42  fe ea d5 dd 44 f9 06 40  |....!..B....D..@|
00000010  1a 42 e7 9f                                       |.B..|
XOR-MAPPED-ADDRESS attribute:
00000000  00 20 00 08 00 01 ce 20  ea 12 d5 45              |. ..... ...E|
decoded back: 203.0.113.7:61234

00 01 is the Binding Request type, 00 00 the message length, 21 12 a4 42 the magic cookie, the next 12 bytes the transaction ID. In the attribute, 00 20 is XOR-MAPPED-ADDRESS, 00 08 its length, 00 01 the family (IPv4), ce 20 the port XORed with the top 16 bits of the cookie (0xCE20 ^ 0x2112 = 0xEF32 = 61234), ea 12 d5 45 the address XORed with the cookie.

The protocol part of hole punching runs locally (on loopback no NAT exists, so it proves the message flow, not the NAT behaviour):

go
// UDP hole punching, run locally. A rendezvous server tells each peer the
// public address it observed for the other peer; both then send to each
// other at the same time. On a real pair of NATs the first outbound packet
// creates the mapping that lets the other side's packet in. On loopback there
// is no NAT, so this demonstrates the protocol, not the NAT behaviour.
package main

import (
	"fmt"
	"net"
	"strings"
	"sync"
	"time"
)

func rendezvous(wg *sync.WaitGroup, ready chan<- string) {
	defer wg.Done()
	conn, _ := net.ListenPacket("udp", "127.0.0.1:0")
	defer conn.Close()
	ready <- conn.LocalAddr().String()
	seen := map[string]net.Addr{}
	buf := make([]byte, 512)
	conn.SetDeadline(time.Now().Add(3 * time.Second))
	for len(seen) < 2 {
		n, from, err := conn.ReadFrom(buf)
		if err != nil {
			return
		}
		seen[string(buf[:n])] = from // "REGISTER name"
	}
	// Tell each peer where the other one appears from the outside.
	for name, addr := range seen {
		for other, oaddr := range seen {
			if other != name {
				conn.WriteTo([]byte("PEER "+oaddr.String()), addr)
			}
		}
	}
}

func peer(name, server string, wg *sync.WaitGroup, out chan<- string) {
	defer wg.Done()
	conn, _ := net.ListenPacket("udp", "127.0.0.1:0") // ONE socket for server and peer traffic
	defer conn.Close()
	srv, _ := net.ResolveUDPAddr("udp", server)
	conn.WriteTo([]byte("REGISTER "+name), srv)

	buf := make([]byte, 512)
	conn.SetReadDeadline(time.Now().Add(2 * time.Second))
	n, _, err := conn.ReadFrom(buf)
	if err != nil {
		out <- name + ": no answer from rendezvous"
		return
	}
	other, _ := net.ResolveUDPAddr("udp", strings.TrimPrefix(string(buf[:n]), "PEER "))
	// Punch: send immediately; a real NAT creates the mapping on this first packet.
	for i := 0; i < 3; i++ {
		conn.WriteTo([]byte("HELLO from "+name), other)
		time.Sleep(50 * time.Millisecond)
	}
	for {
		conn.SetReadDeadline(time.Now().Add(time.Second))
		n, from, err := conn.ReadFrom(buf)
		if err != nil {
			out <- name + ": nothing received from peer"
			return
		}
		if from.String() == other.String() {
			out <- fmt.Sprintf("%s: got %q from %s", name, buf[:n], from)
			return
		}
	}
}

func main() {
	var wg sync.WaitGroup
	ready := make(chan string, 1)
	wg.Add(1)
	go rendezvous(&wg, ready)
	server := <-ready
	out := make(chan string, 2)
	wg.Add(2)
	go peer("alice", server, &wg, out)
	go peer("bob", server, &wg, out)
	wg.Wait()
	close(out)
	for line := range out {
		fmt.Println(line)
	}
}
alice: got "HELLO from bob" from 127.0.0.1:50659
bob: got "HELLO from alice" from 127.0.0.1:49384

WireGuard and keepalive. A NAT row dies when it is idle. WireGuard is silent when there is nothing to send, so a peer behind NAT that only wants to RECEIVE will stop being reachable once the row expires. The WireGuard quick start says: "if a peer is behind NAT or a firewall and he wants to receive incoming packets, he must keep the NAT/firewall mapping valid, by periodically sending keepalive packets. This is called persistent keepalives", with "a sensible interval that works with a wide variety of firewalls is 25 seconds" (PersistentKeepalive = 25, default 0 = off). The same rule applies to SSH (ServerAliveInterval 30), TCP keepalive (tcp_keepalive_time, default 7200 s: far longer than a consumer NAT's UDP timeout), long-lived WebSockets (ping frames) and database connections through a NAT gateway.

ToolTraversal methodRelay fallback
WebRTC (browsers)ICE with STUNTURN (coturn, Cloudflare, Twilio)
TailscaleHole punching, coordinated by the control planeDERP relays
WireGuard (plain)Endpoint roaming + PersistentKeepalive; one side needs a reachable endpointNone (use a relay peer)
Skype / gamesProprietary STUN-like + relaysSuper-nodes / servers
cloudflared / ngrokOutbound-only reverse tunnel to the vendor edgeThe edge is the relay
UPnP-IGD / NAT-PMP / PCPAsk the router to create a forwardN/A

Protocols that embed IPs: ALGs Good to know ​

In plain words: Some protocols put IP addresses inside their payload, not just in the IP header. NAT rewrites the header but not the payload, so the application tells its peer an address that is wrong.

Common misunderstanding: "NAT is transparent to applications." It is, for protocols that only use the headers (HTTP, TLS). It is not for FTP active mode, SIP/RTP, IRC DCC, H.323 and anything carrying an address in its data.

Definition: An Application Layer Gateway (ALG) is code in the NAT that understands such a protocol and rewrites its payload (and keeps the table in sync). RFC 3022: "FTP is the most popular ALG resident on NAT devices", and notes that applications needing an ALG "must not have their payload encoded", since encryption hides the addresses from it.

FTP active mode through NAT
1  client 192.168.1.10 -> server: PORT 192,168,1,10,195,80      (client says: connect back to 192.168.1.10:50000)
2  NAT (no ALG) forwards the line unchanged
3  server tries 192.168.1.10:50000 -> unreachable (private address)
With an ALG: NAT rewrites the line to PORT 203,0,113,7,195,80 and installs a forward for it
ProtocolWhat embeds an addressFix
FTP active (PORT/EPRT)Data-connection address in the control channelUse passive mode (PASV, client dials out) or the nf_conntrack_ftp helper
SIP / SDP / RTPContact, c= line and RTP ports in the signalling bodySIP ALG (often buggy: disable on routers), STUN/ICE, SBC
H.323, IRC DCC, TFTPCallback portsConntrack helpers (nf_conntrack_*)
IPsec ESPNo ports to rewriteNAT-T: ESP in UDP 4500
TLS-wrapped protocolsAddress hidden by encryptionALG impossible: use passive modes or tunnels

On modern Linux, automatic helper assignment is off by default for security (net.netfilter.nf_conntrack_helper=0); you attach a helper explicitly with a CT target. A frequent real bug: a router's "SIP ALG" rewrites correct headers into wrong ones, so VoIP gets one-way audio; the fix is to disable the ALG.

NAT in Kubernetes Must-know ​

In plain words: Pods talk to each other with their own IPs and no NAT, but anything leaving the cluster is SNATed to the node's address, and anything entering through a NodePort or LoadBalancer is DNATed to a pod, and often SNATed too.

Common misunderstanding: "My pod sees the real client IP." Not by default. The Kubernetes tutorial describes the NodePort path: the node replaces "the source IP address (SNAT) in the packet with its own IP address" and "replaces the destination IP on the packet with the pod IP", so the pod sees the node's IP.

Definition: kube-proxy implements Services as DNAT rules (iptables or IPVS, covered in Kubernetes networking); the cluster network is flat for pod to pod; leaving the cluster needs masquerading by the node (or the CNI / cloud NAT).

Pod -> internet                      Client -> NodePort                      Client -> NodePort, Local policy
10.244.1.5 -> 93.184.216.34          198.51.100.23 -> node2:30080            198.51.100.23 -> node2:30080
node SNAT: src = node IP              node2: SNAT src -> node2, DNAT -> pod   node2: DNAT -> local pod only, src kept
(cloud: then NAT gateway SNAT)        pod sees node2's IP as client           pod sees 198.51.100.23; no endpoint -> dropped
SettingClient IP seen by the podCost
externalTrafficPolicy: Cluster (default)The node's IP (SNAT)Extra hop between nodes possible; even load spread
externalTrafficPolicy: LocalThe real client IP"kube-proxy only proxies requests to local endpoints, and does not forward traffic to other nodes"; nodes without a pod drop traffic; uneven load
internalTrafficPolicy: Localn/a (in-cluster)Only node-local endpoints for cluster-internal traffic
Service type LoadBalancer with PROXY protocolReal client via headerNeeds the LB and the app/ingress both configured
Ingress controller sets X-Forwarded-ForReal client in headerApp must trust the ingress only

The Kubernetes docs say of the Local policy: "This approach preserves the original source IP address." To see the other side, run kubectl edit svc NAME and set spec.externalTrafficPolicy to Local.

Egress questionAnswer
What IP does a pod's outbound traffic come from?The node's IP, or the cloud NAT gateway's Elastic IP in a private subnet
How do I give a service a stable egress IP for a partner allow-list?Route private subnets through a NAT gateway with a known Elastic IP; or an egress gateway (Cilium Egress Gateway, Istio egress, Calico egress); or a dedicated node pool
Who masquerades?ip-masq-agent (GKE), the AWS VPC CNI (AWS_VPC_K8S_CNI_EXTERNALSNAT), Cilium (bpf.masquerade), Calico (natOutgoing), flannel (--ip-masq)
Why do some pod IPs look like 10.x to a database in the same VPC?VPC-native CNIs give pods real VPC addresses; no SNAT inside the VPC

NAT in the cloud Important ​

In plain words: In a private subnet, instances have only private addresses. To reach the internet they go through a NAT gateway, which has a public (Elastic) IP. Public instances use an Internet gateway, which does 1:1 NAT for them.

Common misunderstanding: "The NAT gateway also lets the internet in." No: a NAT gateway only supports outbound-initiated flows. Inbound goes through a load balancer or a public instance.

Definition: AWS "NAT gateway" lets private subnets reach out; the Internet gateway "logically provides the one-to-one NAT on behalf of your instance". The NAT gateway pricing page's own worked example bills "a charge of $0.045 per hour" for the gateway and "$0.045" for each GB processed in its example region; the data processing charge comes on top of normal data transfer, which is why a chatty private subnet pulling container images and calling SaaS APIs through NAT can cost real money.

CloudOutbound from private subnetInboundEgress IP
AWSNAT gateway (zonal or regional), or NAT instanceALB/NLB, public IP + Internet gatewayElastic IP on the NAT gateway
GCPCloud NAT (managed, no gateway VM)Load balancers, external IPReserved external IPs on Cloud NAT
AzureNAT Gateway (per subnet) / default outboundLoad balancer, public IPPublic IP on the NAT Gateway
DigitalOcean / HetznerDroplet public IP; NAT via a gateway server or NAT gateway (VPC)Floating / Reserved IPThe reserved IP
Cost leverWhat to do
Per-GB processing on NATGateway VPC endpoints (S3, DynamoDB), interface endpoints (PrivateLink) for AWS APIs, an ECR pull-through cache
One NAT per AZReliability vs hourly fee; do not route AZ-a traffic through AZ-b's NAT (cross-AZ transfer cost)
Port exhaustionAWS: "Each new IPv4 address can support up to 55,000 concurrent connections" on a NAT gateway; add addresses, reuse connections, watch the IdleTimeoutCount CloudWatch metric and close idle connections
IPv6Use an egress-only internet gateway: no NAT, no per-GB NAT charge

Lost client IPs: X-Forwarded-For and PROXY protocol Must-know ​

In plain words: After NAT or any proxy, the server sees the last hop's address. To learn the real client, the last hop must tell you, and you must only believe it from hops you control.

Common misunderstanding: "X-Forwarded-For is the client IP." It is a list the client can write into. The leftmost entry is attacker-controlled; only the entries added by YOUR proxies are trustworthy.

Definition: NAT itself cannot return the client address to the application (it rewrites in the other direction, and for DNAT with SNAT the source is already replaced). Two application-level fixes: the HTTP header X-Forwarded-For (a de facto header, standardised as Forwarded, RFC 7239) appended by each proxy: X-Forwarded-For: <client>, <proxy1>, <proxyN>; and the PROXY protocol, which, in the spec's words, exists because "relaying TCP connections through proxies generally involves a loss of the original TCP connection parameters such as source and destination addresses, ports".

Client 198.51.100.23 -> CDN 203.0.113.50 -> LB 10.0.0.5 -> app 10.0.2.8
App receives:  REMOTE_ADDR=10.0.0.5          X-Forwarded-For: 198.51.100.23, 203.0.113.50
Trusted proxies configured: 10.0.0.0/8 and the CDN ranges.
Right-to-left: 203.0.113.50 (trusted CDN) -> next 198.51.100.23 is not trusted -> that is the client.
Forged:        X-Forwarded-For: 1.2.3.4, 198.51.100.23, 203.0.113.50 -> still 198.51.100.23.
MechanismLayerFormatSpoof riskWhere used
X-Forwarded-ForHTTPComma list, leftmost = clientHigh unless right-to-left with trusted hopsnginx, ALB, Cloudflare (CF-Connecting-IP), most CDNs
Forwarded (RFC 7239)HTTPfor=198.51.100.23;proto=httpsSameNewer proxies
X-Real-IPHTTPSingle valueSamenginx
PROXY protocol v1TCPOne text line PROXY TCP4 src dst sport dport\r\nOnly accept from trusted peersHAProxy, nginx, AWS NLB, Envoy
PROXY protocol v2TCPBinary header + TLVs (12-byte signature)SameAWS NLB, HAProxy
externalTrafficPolicy: LocalL3/L4No header: source preservedNoneKubernetes NodePort / LB
Direct Server Return / transparent proxy (TPROXY)L3Source preservedNoneL4 load balancers
Cloud LB preserving source IPL4NLB with client IP preservationNoneAWS NLB targets by instance ID

Go: read the real IP from a PROXY v1 header, but only from a trusted peer. The snippet's run:

go
// Reading the real client IP from a PROXY protocol v1 header, safely: the
// header is only honoured when the TCP peer is a proxy we trust. Anyone else
// could forge it and pretend to be any address.
package main

import (
	"bufio"
	"errors"
	"fmt"
	"net"
	"net/netip"
	"strconv"
	"strings"
)

var trusted = []netip.Prefix{netip.MustParsePrefix("127.0.0.0/8"), netip.MustParsePrefix("10.0.0.0/8")}

func isTrusted(a netip.Addr) bool {
	for _, p := range trusted {
		if p.Contains(a.Unmap()) {
			return true
		}
	}
	return false
}

// ParseV1 parses "PROXY TCP4 src dst sport dport\r\n" (max 107 bytes per the spec).
func ParseV1(line string) (src netip.AddrPort, err error) {
	if len(line) > 107 {
		return src, errors.New("header longer than 107 bytes")
	}
	f := strings.Fields(strings.TrimRight(line, "\r\n"))
	if len(f) == 2 && f[0] == "PROXY" && f[1] == "UNKNOWN" {
		return src, errors.New("UNKNOWN: use the socket address")
	}
	if len(f) != 6 || f[0] != "PROXY" || (f[1] != "TCP4" && f[1] != "TCP6") {
		return src, errors.New("malformed PROXY line")
	}
	ip, err := netip.ParseAddr(f[2])
	if err != nil {
		return src, err
	}
	port, err := strconv.ParseUint(f[4], 10, 16)
	if err != nil {
		return src, err
	}
	return netip.AddrPortFrom(ip, uint16(port)), nil
}

// ClientAddr returns the address to log, rate-limit and authorise on.
func ClientAddr(conn net.Conn, r *bufio.Reader) (netip.AddrPort, string, error) {
	peer := conn.RemoteAddr().(*net.TCPAddr).AddrPort()
	if !isTrusted(peer.Addr()) {
		return peer, "socket peer (not a trusted proxy, header ignored)", nil
	}
	line, err := r.ReadString('\n')
	if err != nil {
		return peer, "", err
	}
	src, err := ParseV1(line)
	if err != nil {
		return peer, "", err
	}
	return src, "PROXY header from trusted proxy " + peer.Addr().String(), nil
}

func main() {
	ln, _ := net.Listen("tcp", "127.0.0.1:0")
	defer ln.Close()
	go func() {
		c, _ := net.Dial("tcp", ln.Addr().String())
		fmt.Fprint(c, "PROXY TCP4 198.51.100.23 203.0.113.7 54321 443\r\nGET / HTTP/1.1\r\n\r\n")
		c.Close()
	}()
	conn, _ := ln.Accept()
	r := bufio.NewReader(conn)
	addr, why, err := ClientAddr(conn, r)
	fmt.Println("client:", addr, "| via:", why, "| err:", err)

	for _, bad := range []string{"PROXY TCP4 not-an-ip 1.1.1.1 1 2\r\n", "GET / HTTP/1.1\r\n", "PROXY UNKNOWN\r\n"} {
		_, err := ParseV1(bad)
		fmt.Printf("%q -> %v\n", bad, err)
	}
}
client: 198.51.100.23:54321 | via: PROXY header from trusted proxy 127.0.0.1 | err: <nil>
"PROXY TCP4 not-an-ip 1.1.1.1 1 2\r\n" -> ParseAddr("not-an-ip"): unable to parse IP
"GET / HTTP/1.1\r\n" -> malformed PROXY line
"PROXY UNKNOWN\r\n" -> UNKNOWN: use the socket address

And the HTTP side, walking X-Forwarded-For from the right:

go
// Reading the real client IP from X-Forwarded-For safely.
// The header is a list appended to by every proxy: "client, proxy1, proxy2".
// The leftmost entries are controlled by the CLIENT and can be forged. Walk
// from the RIGHT, skipping only addresses of proxies you operate.
package main

import (
	"fmt"
	"net"
	"net/http"
	"net/netip"
	"strings"
)

type Resolver struct{ Trusted []netip.Prefix }

func (r Resolver) trusted(a netip.Addr) bool {
	for _, p := range r.Trusted {
		if p.Contains(a) {
			return true
		}
	}
	return false
}

// ClientIP returns the first address, from the right, that is not a trusted proxy.
func (r Resolver) ClientIP(req *http.Request) netip.Addr {
	host, _, err := net.SplitHostPort(req.RemoteAddr)
	if err != nil {
		host = req.RemoteAddr
	}
	peer, err := netip.ParseAddr(host)
	if err != nil {
		return netip.Addr{}
	}
	peer = peer.Unmap()
	if !r.trusted(peer) {
		return peer // directly connected stranger: ignore any header they sent
	}
	var chain []string
	for _, v := range req.Header.Values("X-Forwarded-For") {
		chain = append(chain, strings.Split(v, ",")...)
	}
	for i := len(chain) - 1; i >= 0; i-- {
		a, err := netip.ParseAddr(strings.TrimSpace(chain[i]))
		if err != nil {
			return peer // garbage in the chain: do not guess
		}
		a = a.Unmap()
		if !r.trusted(a) {
			return a
		}
	}
	return peer
}

func main() {
	res := Resolver{Trusted: []netip.Prefix{netip.MustParsePrefix("10.0.0.0/8")}}
	cases := []struct{ remote, xff string }{
		{"10.0.0.5:4000", "198.51.100.23"},
		{"10.0.0.5:4000", "1.2.3.4, 198.51.100.23"},  // client forged the first hop
		{"10.0.0.5:4000", "198.51.100.23, 10.0.1.9"}, // two trusted proxies
		{"203.0.113.50:5000", "1.2.3.4"},             // no proxy in front: header is a lie
		{"10.0.0.5:4000", "not-an-ip"},
		{"10.0.0.5:4000", ""},
	}
	for _, c := range cases {
		req, _ := http.NewRequest("GET", "http://x/", nil)
		req.RemoteAddr = c.remote
		if c.xff != "" {
			req.Header.Set("X-Forwarded-For", c.xff)
		}
		fmt.Printf("peer=%-18s XFF=%-28q -> %v\n", c.remote, c.xff, res.ClientIP(req))
	}
}
peer=10.0.0.5:4000      XFF="198.51.100.23"              -> 198.51.100.23
peer=10.0.0.5:4000      XFF="1.2.3.4, 198.51.100.23"     -> 198.51.100.23
peer=10.0.0.5:4000      XFF="198.51.100.23, 10.0.1.9"    -> 198.51.100.23
peer=203.0.113.50:5000  XFF="1.2.3.4"                    -> 203.0.113.50
peer=10.0.0.5:4000      XFF="not-an-ip"                  -> 10.0.0.5
peer=10.0.0.5:4000      XFF=""                           -> 10.0.0.5

DHCP: the DORA exchange Must-know ​

In plain words: A device with no address shouts "is there a DHCP server?" (Discover); a server answers with a proposal (Offer); the device says "I'll take that one" (Request); the server confirms (Acknowledge). The result is an address, gateway, DNS and a lease time.

Common misunderstanding: "DHCP gives the address forever." It is a lease: it expires and the device must renew. "DHCP is TCP/HTTP." It is UDP: client port 68, server port 67, with broadcasts, because the client has no IP yet.

Definition: RFC 2131. The standard text of step 1: "The client broadcasts a DHCPDISCOVER message on its local physical subnet" and "BOOTP relay agents may pass the message on to DHCP servers not on the same physical subnet". The message format is the BOOTP header (236 bytes, fixed) + the 4-byte magic cookie 63 82 53 63 + TLV options.

Client (no IP)DHCP server1 DISCOVER 0.0.0.0:68 -> 255.255.255.255:67 (broadcast)"anyone? I want an address" + parameter request list2 OFFER yiaddr=10.99.0.150, lease 120 s, router, dnsserver proposes; other servers may also answer3 REQUEST requested-ip=10.99.0.150, server-id=10.99.0.2 (broadcast)client picks ONE offer; the broadcast tells the losing servers to release theirs4 ACK lease confirmed, T1=60 s, T2=105 sclient configures eth0 = 10.99.0.150/24, default route, DNS (after an ARP probe for duplicates)T1 (50% of lease): unicast REQUEST to the same server = renew. T2 (87.5%): broadcast REQUEST = rebind.at T1: REQUEST (unicast)ACK (lease clock restarts)

Byte-level: the snippet builds a DISCOVER, hex-dumps the fixed header and decodes the options it contains.

go
// Build a DHCPDISCOVER (RFC 2131) byte by byte and decode its options.
// Shows why DHCP is "BOOTP plus options": a fixed 236-byte header, a magic
// cookie, then TLV options.
package main

import (
	"encoding/binary"
	"encoding/hex"
	"fmt"
	"net"
)

const (
	optSubnet   = 1
	optRouter   = 3
	optDNS      = 6
	optDomain   = 15
	optMTU      = 26
	optReqIP    = 50
	optLease    = 51
	optMsgType  = 53
	optServerID = 54
	optParamReq = 55
	optClientID = 61
	optEnd      = 255
)

func discover(mac net.HardwareAddr, xid uint32) []byte {
	b := make([]byte, 236)
	b[0] = 1 // op: BOOTREQUEST
	b[1] = 1 // htype: Ethernet
	b[2] = 6 // hlen
	binary.BigEndian.PutUint32(b[4:], xid)
	binary.BigEndian.PutUint16(b[10:], 0x8000) // flags: BROADCAST (client has no IP yet)
	copy(b[28:], mac)                          // chaddr
	b = append(b, 0x63, 0x82, 0x53, 0x63)      // magic cookie
	b = append(b, optMsgType, 1, 1)            // DHCPDISCOVER
	b = append(b, optClientID, 7, 1)
	b = append(b, mac...)
	b = append(b, optParamReq, 5, optSubnet, optRouter, optDNS, optDomain, optMTU)
	return append(b, optEnd)
}

var names = map[byte]string{1: "subnet-mask", 3: "router", 6: "dns-server", 15: "domain-name", 26: "interface-mtu",
	50: "requested-ip", 51: "lease-time", 53: "message-type", 54: "server-id", 55: "param-request-list", 61: "client-id"}

func decodeOptions(pkt []byte) {
	i := 240 // 236-byte BOOTP header + 4-byte cookie
	for i < len(pkt) && pkt[i] != optEnd {
		code, l := pkt[i], int(pkt[i+1])
		fmt.Printf("  option %3d (%s) len=%d data=%x\n", code, names[code], l, pkt[i+2:i+2+l])
		i += 2 + l
	}
}

func main() {
	mac, _ := net.ParseMAC("02:42:ac:11:00:02")
	pkt := discover(mac, 0xdeadbeef)
	fmt.Printf("DISCOVER is %d bytes; fixed header + cookie:\n%s", len(pkt), hex.Dump(pkt[:48]))
	fmt.Printf("cookie at offset 236: %x\n", pkt[236:240])
	decodeOptions(pkt)
}
DISCOVER is 260 bytes; fixed header + cookie:
00000000  01 01 06 00 de ad be ef  00 00 80 00 00 00 00 00  |................|
00000010  00 00 00 00 00 00 00 00  00 00 00 00 02 42 ac 11  |.............B..|
00000020  00 02 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
cookie at offset 236: 63825363
  option  53 (message-type) len=1 data=01
  option  61 (client-id) len=7 data=010242ac110002
  option  55 (param-request-list) len=5 data=0103060f1a

Offsets: byte 0 01 = op (BOOTREQUEST), 01 = htype Ethernet, 06 = hlen, 00 = hops; de ad be ef = xid (transaction ID that matches replies to requests); 00 00 = secs; 80 00 = flags with the BROADCAST bit set (the client cannot receive unicast before it has an IP); then ciaddr, yiaddr, siaddr, giaddr (all zero in a DISCOVER) and from byte 28 the 16-byte chaddr (client MAC).

Now the real thing. I ran dnsmasq as the server on a throwaway Docker network and udhcpc as the client, with tcpdump -n -v on the server side (trimmed to the essentials):

udhcpc: broadcasting discover
udhcpc: broadcasting select for 10.99.0.150, server 10.99.0.2
udhcpc: lease of 10.99.0.150 obtained from 10.99.0.2, lease time 120

0.0.0.0.68 > 255.255.255.255.67: BOOTP/DHCP, Request from 9a:44:10:cf:86:b4, xid 0x875a3927
    DHCP-Message (53), length 1: Discover
    Parameter-Request (55): Subnet-Mask (1), Default-Gateway (3), Domain-Name-Server (6), Hostname (12), Domain-Name (15), BR (28), NTP (42)
    Client-ID (61): ether 9a:44:10:cf:86:b4
10.99.0.2.67 > 10.99.0.150.68: BOOTP/DHCP, Reply, xid 0x875a3927
    Your-IP 10.99.0.150  Server-IP 10.99.0.2
    DHCP-Message (53): Offer   Server-ID (54): 10.99.0.2   Lease-Time (51): 120
    RN (58): 60   RB (59): 105   Subnet-Mask (1): 255.255.255.0   Domain-Name (15): "lab.test"
    Domain-Name-Server (6): 10.99.0.53   Default-Gateway (3): 10.99.0.1
0.0.0.0.68 > 255.255.255.255.67: BOOTP/DHCP, Request from 9a:44:10:cf:86:b4, xid 0x875a3927
    DHCP-Message (53): Request   Requested-IP (50): 10.99.0.150   Server-ID (54): 10.99.0.2
10.99.0.2.67 > 10.99.0.150.68: BOOTP/DHCP, Reply, xid 0x875a3927
    Your-IP 10.99.0.150   DHCP-Message (53): ACK   Lease-Time (51): 120   RN (58): 60   RB (59): 105

Things visible only in the real capture: the DISCOVER and REQUEST come from 0.0.0.0 to 255.255.255.255 (broadcast), while the OFFER and ACK are unicast to the offered address (10.99.0.2.67 > 10.99.0.150.68, since the client set no broadcast flag and the server could reach the MAC directly); the xid stays the same through the whole exchange; the first DISCOVER was repeated after 3 seconds (secs 3) because the client retransmits until it gets an OFFER; and RN/RB are the renewal (T1 = 60 s) and rebinding (T2 = 105 s) timers, 50% and 87.5% of the 120 s lease. The client also asked for option 28 (broadcast) and 42 (NTP) that this server did not have. It did not ask for option 26 (interface MTU), so dnsmasq did not send the MTU configured on the server: options are sent only when requested (or forced with dhcp-option-force).

On macOS the lease is visible with ipconfig getpacket en0 (real output from this machine on a phone hotspot, MAC masked):

op = BOOTREPLY
xid = 0xa09a3e49
ciaddr = 10.84.50.174
yiaddr = 10.84.50.174
siaddr = 10.84.50.254
chaddr = xx:xx:xx:xx:xx:xx
options:
dhcp_message_type (uint8): ACK 0x5
server_identifier (ip): 10.84.50.254
lease_time (uint32): 0xe0f          # 3599 s
renewal_t1_time_value (uint32): 0x707   # 1799 s
rebinding_t2_time_value (uint32): 0xc4d # 3149 s
subnet_mask (ip): 255.255.255.0
router (ip_mult): {10.84.50.254}
domain_name_server (ip_mult): {10.84.50.254}
Client toolShow the leaseRenewRelease
macOSipconfig getpacket en0sudo ipconfig set en0 DHCPSystem Settings, "Renew DHCP Lease"
Linux NetworkManagernmcli -f DHCP4 device show eth0nmcli device reapply eth0nmcli connection down id <name>
Linux dhclient/var/lib/dhcp/dhclient.leasessudo dhclient -v eth0sudo dhclient -r eth0
systemd-networkdnetworkctl status eth0networkctl renew eth0networkctl reconfigure eth0
dhcpcddhcpcd -U eth0dhcpcd -n eth0dhcpcd -k eth0
BusyBoxudhcpc -i eth0 -f -nrerun-R
Windowsipconfig /allipconfig /renewipconfig /release

Leases, renewals and options Must-know ​

In plain words: A lease is a rental. Halfway through, the device asks the same server to extend it. If that fails it asks anyone. If everything fails it gives up the address at the end.

Common misunderstanding: "My server's IP will not change after a reboot." It usually will not (the server remembers by MAC or client ID), but it can: when the lease expired while the machine was off, the pool was exhausted, the lease database was wiped, or the NIC changed.

Definition: RFC 2131: T1 "defaults to (0.5 * duration_of_lease)" and T2 to "(0.875 * duration_of_lease)". At T1 the client unicasts a REQUEST to the server that gave the lease; at T2 it broadcasts to any server; at expiry it must stop using the address and restart from DISCOVER.

lease 3600 s   (T1 = 1800 s, T2 = 3150 s)
t=0        ACK            address configured
t=1800     REQUEST (unicast to server) -> ACK        lease restarts, timers reset
(server unreachable at T1)
t=3150     REQUEST (broadcast) -> any server may ACK/NAK
t=3600     lease expires -> deconfigure interface, DISCOVER again
NAK: server says "that address is no longer valid" -> client restarts at DISCOVER
Option (code)NameWhat it configuresNotes
1Subnet maskThe netmaskUse with option 3
3RouterDefault gatewayList, first preferred
6Domain name serverDNS resolversBecomes /etc/resolv.conf
12HostnameClient's nameUsed for DDNS, DNS registration
15Domain nameSearch domainlab.test in the lab
26Interface MTULink MTUNeeded for overlays and tunnels; only sent if requested
28Broadcast addressDerivable from address and mask
42NTP serversTime sync
43Vendor specifice.g. ANDROID_METERED on hotspotsOpaque
50Requested IPChosen address in REQUEST
51Lease timeSeconds
53DHCP message type1 Discover, 2 Offer, 3 Request, 4 Decline, 5 ACK, 6 NAK, 7 Release, 8 Inform
54Server identifierWhich serverPicks one offer
55Parameter request listWhich options the client wants
58 / 59T1 / T2Renewal / rebinding
60 / 61Vendor class / client identifierIdentificationUsed for reservations
66 / 67TFTP server / bootfilePXE netboot
82Relay agent informationCircuit and remote IDAdded by relays (RFC 3046)
119Domain search listSeveral search domains
121Classless static routesExtra routes (VPN/split)
252WPADProxy auto-configSecurity-sensitive

Reservations, relay agents, Docker and the cloud Important ​

In plain words: A reservation tells the DHCP server "always give this MAC the same address". A relay forwards broadcasts across routers so one server can serve many subnets. Docker and the cloud do not use DHCP the way a LAN does.

Common misunderstanding: "A DHCP reservation is a static IP." A static IP is configured on the host and the server does not know about it, so it can hand the same address to someone else unless it is outside the pool. A reservation is configured on the server; the host still uses DHCP.

TopicHow it worksProduct detail
Reservation (static lease)Server maps MAC or client ID to a fixed IPdnsmasq: dhcp-host=aa:bb:cc:dd:ee:ff,10.0.0.50,web1; ISC Kea reservations; router UI "Static DHCP"; Windows DHCP "Reservation"
Exclusion / poolAddresses the server never hands outPut static servers outside dhcp-range
Relay agentA router with ip helper-address / dhcrelay receives the broadcast, sets giaddr and unicasts to the DHCP serverAdds option 82 (RFC 3046); server selects the subnet by giaddr
Rogue DHCPAn unauthorised server (a plugged-in home router) answers faster and hands out a wrong gateway or DNS: a man-in-the-middleDHCP snooping on switches (trusted ports), 802.1X, monitor with nmap --script broadcast-dhcp-discover
DHCP in DockerNone: Docker's IPAM assigns the container IP from the network subnet; the container has a static address inside its namespacedocker network create --subnet 10.99.0.0/24; --ip for fixed addresses; macvlan/ipvlan networks can use an external DHCP only via third-party plugins
DHCP in VMsThe hypervisor or virtual network runs onelibvirt virbr0 uses dnsmasq; VirtualBox NAT has a built-in server; Vagrant NAT (10.0.2.15)
DHCP in the cloudThe VPC's virtual DHCP: the instance runs a normal DHCP client, but the address is assigned by the control plane, tied to the ENI; metadata (169.254.169.254) delivers user data and credentialsAWS "DHCP option sets" (DNS servers, domain, NTP); GCP and Azure similar
KubernetesPod IPs come from the CNI's IPAM (not DHCP); nodes use cloud DHCPhost-local, whereabouts, cloud VPC IPAM

DHCPv6 vs SLAAC Good to know ​

In plain words: IPv6 hosts can build their own address from a router's advertised prefix (SLAAC) or ask a server (DHCPv6), or both.

Common misunderstanding: "IPv6 does not need DHCP." SLAAC gives an address and gateway but not DNS (well, RDNSS exists); DHCPv6 can add DNS, NTP and prefixes. Many networks run both.

Definition: SLAAC (Stateless Address Autoconfiguration, RFC 4862): a router sends Router Advertisements (ICMPv6) with a prefix, and the host appends an interface identifier (random "privacy" address, or EUI-64). DHCPv6 (RFC 8415) uses UDP 546 (client) and 547 (server), a different message set (Solicit, Advertise, Request, Reply) and DUIDs instead of MACs. The RA flags M (managed: use DHCPv6 for addresses) and O (other: use DHCPv6 for options only) tell the host which to use.

DHCPv4SLAACDHCPv6 statefulDHCPv6 stateless
Gives addressYesYes, host-generatedYes, from a poolNo
Gives gatewayOption 3Router AdvertisementNo (RA does)No (RA does)
Gives DNSOption 6RDNSS option or noneYesYes
Needs serverYesNo, only a routerYesYes (options only)
Tracking by serverYesNoYesNo
IPv6 and NATUsually no NAT: global addresses

IPv6 reduces the need for NAT (every host can have a global address, firewalls do the filtering), but NAT66/NPTv6 and NAT64/DNS64 (IPv6-only clients reaching IPv4 servers) exist and are common on mobile networks and in IPv6-only Kubernetes clusters.

Addressing choices: static vs dynamic, ephemeral vs fixed ports ​

In plain words: Servers want stable addresses and ports; clients do not care. NAT and firewalls use that asymmetry.

Common misunderstanding: "Opening port 443 on the firewall also opens the client's source port." A client's source port is ephemeral (typically 32768-60999 on Linux, 49152-65535 by IANA), chosen per connection; a stateful firewall allows the reply by looking the flow up in conntrack, not by opening the port.

ChoiceUse forWhy
Static address configured on the hostRouters, DNS servers, DHCP servers, bare-metal databasesMust be reachable even if DHCP is down
DHCP reservationPrinters, NAS, dev boxes, Raspberry PiCentral control, host stays DHCP
Dynamic DHCPLaptops, phones, IoT guestsZero configuration
Cloud private IPVMsAssigned by the VPC, stable for the instance's life; use DNS names
DNS name instead of IPEverything an app connects toSurvives lease and IP changes
Fixed (well-known) portServers: 22, 80, 443, 5432Clients must know it
Ephemeral portClients' sourceChosen from net.ipv4.ip_local_port_range (32768 60999 default)
NAT port rangePer NAT gatewayThe gateway chooses; exhaustion limits connections
Stateful firewall + NAT, both directions
outbound  192.168.1.10:51000 -> 93.184.216.34:443   conntrack ESTABLISHED row created
inbound   93.184.216.34:443 -> 203.0.113.7:40000    matches the row: allowed, even though no rule opens :40000
inbound   198.51.100.99:443 -> 203.0.113.7:40000    different remote: no row: dropped

Mechanics ​

Seeing NAT: commands and what they print ​

What to look atCommand (Linux)Notes
NAT rules, iptables syntaxsudo iptables -t nat -L -n -v --line-numbers or -S-n stops reverse DNS; -v shows packet counters
All nftables rulessudo nft list rulesetiptables-nft rules appear here with a warning
The nat table onlysudo nft list table ip natOnly exists if something created it
Live conntrack tablesudo conntrack -L, conntrack -L -p tcp --dport 8080From conntrack-tools
Count and statsconntrack -C, conntrack -SCompare -C with nf_conntrack_max
Watch eventssudo conntrack -E[NEW], [UPDATE], [DESTROY]
Without the toolcat /proc/net/nf_conntrack
Is forwarding on?sysctl net.ipv4.ip_forwardNAT routers need 1
Which gatewayip route, ip addrDefault route shows the next hop
From inside a containerip route, cat /etc/resolv.conf, curl ifconfig.meShows the container IP and the NAT-ed public IP
Capture NAT in actionsudo tcpdump -ni any host 93.184.216.34Compare the packet on the inside and outside interfaces
macOSipconfig getpacket en0, netstat -rn, sudo pfctl -s nat, sudo pfctl -s statepf replaces iptables
WindowsGet-NetNat, netsh interface portproxy show all

Real iptables -t nat -S (Docker Desktop VM) is in Port forwarding; real conntrack rows are in the table section. From inside the published container (docker exec natlab ip route):

default via 172.17.0.1 dev eth0
172.17.0.0/16 dev eth0 scope link  src 172.17.0.2

and the masquerade of a container's outbound curl http://example.com/ in conntrack (public address trimmed): the original direction has the container as source, the reply direction is addressed to the VM, not to the container:

tcp 6 102 TIME_WAIT src=172.17.0.2 dst=198.18.1.39 sport=47340 dport=80 src=198.18.1.39 dst=192.168.65.3 sport=80 dport=47340 [ASSURED]

Netfilter order of events ​

packet in
  raw PREROUTING   (can mark NOTRACK)
  conntrack lookup / create
  mangle PREROUTING
  nat PREROUTING        <- DNAT (port forwards, Docker -p, kube-proxy)
  routing decision
     local  -> filter INPUT  -> process
     other  -> filter FORWARD -> mangle POSTROUTING -> nat POSTROUTING  <- SNAT / MASQUERADE -> out
local process out -> raw OUTPUT -> nat OUTPUT (DNAT for local clients) -> routing -> POSTROUTING

Why this order matters: DNAT happens BEFORE routing, so the routing table decides where the rewritten packet goes; the filter FORWARD chain sees the already-rewritten destination (172.17.0.2:80, not :8080); SNAT happens after everything, so filter rules see the original source.

What each product does ​

ProductNAT implementationPort forwardWhere the table livesNotable default
Linux (iptables / nftables)netfilter + conntrackDNAT + FORWARD acceptkernelnf_conntrack_max = 262144 on the lab VM
Dockeriptables/nft rules per bridge-p, rules in DOCKER chain + docker-proxyhost conntrackMasquerade for every bridge subnet; hairpin rule per port
Kuberneteskube-proxy iptables or IPVS, or Cilium eBPFNodePort, LoadBalancernode conntrack / eBPF mapsexternalTrafficPolicy: Cluster
AWS NAT gatewayManaged, per-AZNone (outbound only)Service-sideConnection and port limits per destination
AWS Internet gateway1:1 NAT for public IP / Elastic IPSecurity groups + routeService-side
GCP Cloud NATSoftware-defined, no VMNoneService-sideMin ports per VM configurable
Home router (Linux/BSD based)netfilter or pfUIRouter RAMUDP timeout 30-60 s, table of a few thousand entries
macOSpfpfctl anchorskernelInternet Sharing uses bootpd for DHCP and pf for NAT
WindowsWinNAT (Get-NetNat)netsh portproxy / NAT static mappingkernelUsed by WSL2 and Hyper-V default switch
Cisco IOSNAT/PATip nat inside source staticrouterPAT is overload
pfSense / OPNsensepfFirewall > NAT > Port ForwardfirewallNAT reflection optional

Solving the classic problems ​

ProblemSolutionHowCost / limitation
Reach an inside service from outsidePort forward / DNATRule on the edge device that owns the public IPNeeds a public IP; one service per port per IP
Same, but behind CGNAT or double NATReverse tunnelcloudflared, ngrok, WireGuard or SSH -R to a VPSDepends on a relay; latency; vendor terms
Application needs the real client IPTrustProxies / right-to-left XFF; PROXY protocol; externalTrafficPolicy: LocalSee Lost client IPsMust define which hops are trusted
Inside client cannot reach the inside server through its public nameSplit-horizon DNS or hairpin NATResolve to the private IP internallyTwo views of DNS to maintain
Long-lived idle connection dies through NATKeepalive shorter than NAT timeoutPersistentKeepalive = 25, TCP keepalive, WebSocket pingA little traffic
NAT table fullRaise nf_conntrack_max, lower timeouts, reuse connections, NOTRACK for known trafficsysctl, poolingMemory per entry
Hard-coded IP breaks after DHCP renewalName instead of IP, or DHCP reservationDNS / dhcp-host=DNS TTL discipline
Peers both behind NATSTUN + ICE + TURNWebRTC, TailscaleA relay costs bandwidth
Stable outbound IP for partner allow-listsNAT gateway with Elastic IP / egress gatewayRoute private subnets through itPer-hour and per-GB cost

A small TCP port forwarder in Go ​

NAT does forwarding in the kernel; this does it in user space (what socat, docker-proxy and ssh -L do). The backend sees the forwarder as the client, so the real address is lost unless the forwarder prepends a PROXY protocol header.

go
// A tiny TCP port forwarder: what `socat TCP-LISTEN:8080,fork TCP:10.0.0.5:80`,
// docker-proxy and an SSH -L tunnel do. It is a layer-4 proxy, not NAT: the
// backend sees THIS process as the client, so the real client IP is lost
// unless we prepend a PROXY protocol v1 header (-proxy-protocol).
package main

import (
	"context"
	"flag"
	"fmt"
	"io"
	"log"
	"net"
	"os"
	"os/signal"
	"sync"
	"time"
)

func main() {
	listen := flag.String("listen", "127.0.0.1:8080", "address to accept on")
	target := flag.String("target", "127.0.0.1:9000", "backend to dial")
	proxyProto := flag.Bool("proxy-protocol", false, "prepend a PROXY v1 header with the real client address")
	flag.Parse()

	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	defer stop()

	ln, err := net.Listen("tcp", *listen)
	if err != nil {
		log.Fatal(err)
	}
	go func() { <-ctx.Done(); ln.Close() }()
	log.Printf("forwarding %s -> %s (proxy-protocol=%v)", *listen, *target, *proxyProto)

	var wg sync.WaitGroup
	for {
		c, err := ln.Accept()
		if err != nil {
			break
		}
		wg.Add(1)
		go func() {
			defer wg.Done()
			handle(c, *target, *proxyProto)
		}()
	}
	wg.Wait()
}

func handle(client net.Conn, target string, proxyProto bool) {
	defer client.Close()
	backend, err := net.DialTimeout("tcp", target, 3*time.Second)
	if err != nil {
		log.Printf("dial %s: %v", target, err)
		return
	}
	defer backend.Close()

	if proxyProto {
		src := client.RemoteAddr().(*net.TCPAddr)
		dst := client.LocalAddr().(*net.TCPAddr)
		fam := "TCP4"
		if src.IP.To4() == nil {
			fam = "TCP6"
		}
		// PROXY protocol v1: one text line before any payload.
		fmt.Fprintf(backend, "PROXY %s %s %s %d %d\r\n", fam, src.IP, dst.IP, src.Port, dst.Port)
	}

	done := make(chan struct{}, 2)
	pipe := func(dst, src net.Conn) {
		io.Copy(dst, src)
		// Half-close so the peer sees EOF but can still finish its reply.
		if tc, ok := dst.(*net.TCPConn); ok {
			tc.CloseWrite()
		}
		done <- struct{}{}
	}
	go pipe(backend, client)
	go pipe(client, backend)
	<-done
	<-done
}

Real run: a Python http.server on :9000, the forwarder on :8081, then curl through it; and with -proxy-protocol in front of a nc -l listener, what the backend receives is a one-line header before the payload:

$ /tmp/fwd -listen 127.0.0.1:8081 -target 127.0.0.1:9000
$ curl -s -o /dev/null -w "via forwarder: %{http_code}\n" http://127.0.0.1:8081/
via forwarder: 200
$ /tmp/fwd -listen 127.0.0.1:8082 -target 127.0.0.1:9100 -proxy-protocol
PROXY TCP4 127.0.0.1 127.0.0.1 56172 8082
hello

Storing and classifying client addresses (SQL) ​

Keep real client addresses in a native address type and test them against the special ranges. PostgreSQL's inet type and the <<= ("is contained within or equals") operator make CGNAT and private-range checks one line:

sql
CREATE TABLE login_events (
  id        bigserial PRIMARY KEY,
  user_id   bigint NOT NULL,
  client_ip inet   NOT NULL,       -- the REAL client address after trusted-proxy resolution
  proxy_ip  inet,                  -- the TCP peer (load balancer / NAT gateway), for audits
  at        timestamptz NOT NULL DEFAULT now()
);

-- Which logins came from carrier-grade NAT, where one IP = many people?
SELECT client_ip, count(DISTINCT user_id) AS users
FROM login_events
WHERE client_ip <<= '100.64.0.0/10'
GROUP BY client_ip
ORDER BY users DESC;

-- Detect a misconfigured proxy: every row has the same (private) client IP.
SELECT client_ip, count(*) FROM login_events
WHERE at > now() - interval '1 hour'
GROUP BY client_ip HAVING count(*) > 1000;

-- Private or reserved addresses must never be "client" addresses on the public internet.
SELECT count(*) FROM login_events
WHERE client_ip <<= ANY (ARRAY['10.0.0.0/8','172.16.0.0/12','192.168.0.0/16','127.0.0.0/8']::inet[]);

Laravel and PHP behind NAT ​

Laravel reads the client address from the TCP peer unless it is told which proxies to trust. The Laravel docs explain the symptom: behind a load balancer that terminates TLS the app sees plain HTTP on port 80 and generates insecure links; "you may enable the Illuminate\Http\Middleware\TrustProxies middleware ... specified using the trustProxies middleware method in your application's bootstrap/app.php file". In Laravel 13 the configuration is:

php
<?php

// bootstrap/app.php (Laravel 13): tell the framework which hops are YOUR proxies.
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        // Trust only the load balancer / ingress ranges, never '*' on a public host.
        // 10.0.0.0/8 here is the VPC range where the load balancer lives.
        $middleware->trustProxies(
            at: ['10.0.0.0/8', '172.16.0.0/12'],
            headers: Request::HEADER_X_FORWARDED_FOR
                | Request::HEADER_X_FORWARDED_HOST
                | Request::HEADER_X_FORWARDED_PORT
                | Request::HEADER_X_FORWARDED_PROTO,
        );
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        //
    })
    ->create();

A diagnostic route shows what the app really sees; without trustProxies, ip equals remote_addr (the load balancer), with it ip is the client:

php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

// Shows what the application sees behind NAT, a reverse proxy or a load balancer.
class WhoAmIController extends Controller
{
    public function __invoke(Request $request): JsonResponse
    {
        return response()->json([
            // The TCP peer: the load balancer or the NAT gateway, not the user.
            'remote_addr' => $request->server('REMOTE_ADDR'),
            // Real client IP after TrustProxies has walked X-Forwarded-For.
            'ip' => $request->ip(),
            // The full chain Symfony resolved, nearest hop first.
            'ips' => $request->ips(),
            'raw_xff' => $request->header('X-Forwarded-For'),
            'scheme' => $request->getScheme(),
            'secure' => $request->isSecure(),
        ]);
    }
}

Rate limiting by real IP. If TrustProxies is missing, every request has the same ip() (the gateway), so one client's burst locks out everyone. Behind CGNAT the opposite risk exists: one IPv4 is thousands of people, so limit by user where possible, and group IPv6 by prefix:

php
<?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;

class RateLimitServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        // Key on the REAL client IP. If TrustProxies is missing, every request
        // arrives from the NAT gateway or load balancer, the key is one single
        // address and the whole site shares one bucket: one noisy client
        // locks everyone out.
        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
        });

        // Carrier-grade NAT puts thousands of subscribers behind ONE public IPv4.
        // Group IPv6 clients by /64 and keep a roomier per-IP budget for IPv4.
        RateLimiter::for('login', function (Request $request) {
            $ip = $request->ip();
            $key = str_contains($ip, ':')
                ? 'v6:'.substr(bin2hex(inet_pton($ip)), 0, 16) // first 8 bytes = the /64
                : 'v4:'.$ip;

            return [
                Limit::perMinute(5)->by($key.'|'.$request->input('email')),
                Limit::perMinute(30)->by($key),
            ];
        });
    }
}

Webhook servers behind NAT. A laptop or office server cannot receive a provider's webhook because there is no inbound path. A tunnel dials OUT to a vendor edge and the edge forwards inbound requests down that connection: the NAT is bypassed by reversing who opens the connection. With cloudflared, a one-line quick tunnel (random trycloudflare.com URL; the Cloudflare docs say "Quick Tunnels are for testing and development") or the Compose file below; with ngrok, ngrok http 8000. Because the URL is public, verify the signature, never the source IP:

yaml
# A reverse-connection tunnel: the container dials OUT to Cloudflare, so no
# port forward and no public IP are needed. Works behind CGNAT and double NAT.
services:
  app:
    image: nginx:alpine
    expose: ["80"]

  tunnel:
    image: cloudflare/cloudflared:latest
    # Quick tunnel (random trycloudflare.com URL, for demos only).
    command: tunnel --no-autoupdate --url http://app:80
    depends_on: [app]
php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;

// A webhook receiver behind NAT is reached through an outbound tunnel
// (cloudflared, ngrok). The public URL is not trustworthy by itself, so verify
// a signature instead of trusting the source IP.
class WebhookController extends Controller
{
    public function __invoke(Request $request): Response
    {
        $payload = $request->getContent();
        $expected = hash_hmac('sha256', $payload, config('services.provider.webhook_secret'));
        $given = (string) $request->header('X-Signature', '');

        if (! hash_equals($expected, $given)) {
            return response('invalid signature', 401);
        }

        // Acknowledge fast, process in a queue: the tunnel and the sender both time out.
        dispatch(new \App\Jobs\HandleWebhook(json_decode($payload, true, 512, JSON_THROW_ON_ERROR)));

        return response('', 202);
    }
}

And an Artisan command to tell "refused" (a host answered, nothing listens) from "no answer" (dropped by NAT, a firewall or CGNAT), to run from outside the network:

php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

// php artisan net:check-port 198.51.100.7 8080
// Run it from OUTSIDE the network (a VPS, a phone hotspot) to test a port forward.
class CheckPortCommand extends Command
{
    protected $signature = 'net:check-port {host} {port : TCP port} {--timeout=3}';
    protected $description = 'Tell connection refused from timeout (what each means for NAT and firewalls)';

    public function handle(): int
    {
        $errno = 0;
        $err = '';
        $start = microtime(true);
        $s = @stream_socket_client(
            sprintf('tcp://%s:%d', $this->argument('host'), (int) $this->argument('port')),
            $errno,
            $err,
            (float) $this->option('timeout'),
        );
        $ms = round((microtime(true) - $start) * 1000);

        if ($s) {
            fclose($s);
            $this->info("open ({$ms} ms): the forward and the service work");

            return self::SUCCESS;
        }

        // errno 111 = ECONNREFUSED: a host answered with RST (forward reaches a machine, nothing listens).
        // errno 110 / timeout: packets were dropped silently (no forward, firewall, CGNAT, wrong IP).
        $this->error($errno === 111
            ? "refused ({$ms} ms): reached a host, nothing listening on that port"
            : "no answer ({$ms} ms, errno {$errno}): dropped by NAT, a firewall or CGNAT");

        return self::FAILURE;
    }
}
Laravel APIWhat it doesNote
$middleware->trustProxies(at: [...], headers: ...)Declares trusted proxy IPs/CIDRs and which X-Forwarded-* headers to believeat: '*' trusts everyone: unsafe on a public host
Request::ip() / $request->ip()Real client IP after trusted-proxy resolutionEquals REMOTE_ADDR if no proxy is trusted
$request->ips()Full chain of client + proxiesUseful for audits
RateLimiter::for() / Limit::perMinute()->by()Named limiters; ->by() sets the keyUse user id first, then ip
hash_equals()Constant-time signature comparisonFor webhooks
php artisan serve / OctaneListens on 127.0.0.1 / 0.0.0.0Bind explicitly in containers

Choosing ​

SituationRecommendationExtra techniqueReason
Home lab with a real public IPPort forward plus DDNS and TLSFail2ban, non-default SSH port, VPN for adminSimple, but exposed to scans
Home lab behind CGNATOutbound tunnel (cloudflared, Tailscale, WireGuard to a VPS)Or ask the ISP for a public IP / use IPv6Inbound is impossible
Webhook developmentcloudflared / ngrok quick tunnelSignature verificationPublic URL without router changes
Production behind a load balancerTrustProxies with the LB's CIDRPROXY protocol on L4 LBsReal client IP for logs and limits
Pods need a partner-whitelisted IPNAT gateway with Elastic IP / egress gatewayCilium Egress GatewayOne stable address
High-volume outbound to AWS APIsVPC endpointsPer-AZ NAT only for the restNAT per-GB cost
Real-time P2P (video, games)WebRTC with STUN + TURNcoturn, TailscaleDirect when possible, relay otherwise
Servers on the LANStatic IP outside the pool, or DHCP reservationDNS namesPredictable addresses
Containers need fixed IPsUser-defined network --ip or DNS namesCompose service namesDocker's IPAM, not DHCP
Many customers behind one IPv4Per-user limits, IPv6CGNAT makes IP a weak identity

In architecture: from a single process to a distributed system ​

Monolith (one process, one database) ​

Example. A Laravel app on one VPS with a public IP. A cloud firewall allows 80/443; nginx proxies to PHP-FPM on 127.0.0.1:9000. There is no NAT in the path, $request->ip() is the client, and logging and rate limiting just work. The moment you put Cloudflare or a load balancer in front, REMOTE_ADDR becomes the proxy and you must configure trustProxies with that proxy's ranges. In the office, the developers' laptops are behind a PAT router and all reach the staging server from the same public IP, which is why staging allow-lists are keyed on that address.

Modular monolith ​

Example. Several modules (billing, auth, reporting) share a deployment and talk in-process, but they call external providers (payments, email) over the internet from a private subnet. All outbound calls leave through one NAT gateway, so every provider sees one stable IP. Allow-listing for the payment provider uses that Elastic IP; losing the gateway (or recreating it with a new address) breaks the allow-list, so treat it as a managed asset. Webhooks from the providers come inbound through the load balancer, not through the NAT gateway.

Microservices ​

Example. An order service in Kubernetes calls a partner API and receives webhooks. Pod-to-pod traffic is not NATed; the partner API call is SNATed to the node and then to the NAT gateway's Elastic IP (two SNATs, the partner sees one IP). The Ingress sets X-Forwarded-For; the order service trusts only the ingress CIDR. Internal audit logs store client_ip (resolved), proxy_ip (peer) and the trace id, using the inet columns shown above. The service-to-service hop goes by DNS name; hard-coded pod IPs are a bug, because a pod gets a new IP on every restart. Service meshes and mTLS add identity so that "source IP" stops being the only way to say who called (mTLS).

Distributed data: replicas, caches, multi-region ​

Example. A database replica in another region, reached through a VPN or peering. NAT gateways in the path will silently drop idle connections: PostgreSQL replication or a pooled connection that idles longer than the NAT's timeout (350 seconds for the AWS NAT gateway, per its troubleshooting page) times out; the NAT gateway then answers the next packet with an RST (its troubleshooting page: "a NAT gateway returns an RST packet to any resources behind the NAT gateway that attempt to continue the connection"), so the app sees connection reset on the next query instead of a clean close. Defence: TCP keepalives shorter than the NAT timeout (tcp_keepalives_idle=60 in the Postgres client), pool health checks, and statement_timeout. For caches (Redis) the same applies to long-lived pub/sub connections. Multi-region active-active systems prefer private connectivity (peering/transit) over NAT because the table is state that cannot be replicated between two NAT devices: a failover loses every flow.

Scaling path ​

LoadWhat breaks firstWhat to change
1x (hundreds of connections)Nothing; one NAT, one public IPDefaults are fine
10x (tens of thousands of connections)conntrack table fills on the NAT box or Docker/K8s node; hairpin and TrustProxies mistakes show up as skewed logsRaise nf_conntrack_max, keep-alive and pooling, externalTrafficPolicy: Local or PROXY protocol
100x (millions of short outbound calls)NAT gateway port exhaustion (about 55,000 concurrent connections per attached IPv4 address) and per-GB costMore Elastic IPs, regional NAT, VPC endpoints, connection reuse, IPv6 egress
Global scaleNAT as a single point; asymmetric routing breaks state; CGNAT makes IP a poor identityAnycast + L4 load balancers with source preservation (DSR), IPv6, identity-based limits

Lab ​

All commands ran on Docker Desktop (a Linux VM); on a Linux host drop the docker run --net=host helper and use sudo directly. Output below is real.

1. Publish a port and read the rules.

bash
docker run -d --name natlab -p 8080:80 nginx:alpine
docker run --rm --net=host --cap-add NET_ADMIN alpine sh -c 'apk add -q iptables >/dev/null; iptables -t nat -S'
# expect (among others):
# -A DOCKER -p tcp -m tcp --dport 8080 -j DNAT --to-destination 172.17.0.2:80
# -A POSTROUTING -s 172.17.0.0/16 ! -o docker0 -j MASQUERADE
# -A POSTROUTING -s 172.17.0.2/32 -d 172.17.0.2/32 -p tcp -m tcp --dport 80 -j MASQUERADE

2. Watch conntrack during a request.

bash
docker run --rm --net=host --cap-add NET_ADMIN alpine sh -c '
  apk add -q conntrack-tools >/dev/null
  (printf "GET / HTTP/1.1\r\nHost: x\r\n\r\n"; sleep 4) | nc 127.0.0.1 8080 >/dev/null &
  sleep 1; conntrack -L -p tcp | grep dport=8080; conntrack -C'
# expect: tcp 6 431998 ESTABLISHED src=127.0.0.1 dst=127.0.0.1 sport=56997 dport=8080 src=172.17.0.2 dst=172.17.0.1 sport=80 dport=56997 [ASSURED]
# the reply tuple already shows the container (172.17.0.2:80): that is the DNAT

3. Reproduce the hairpin failure.

bash
docker exec natlab sh -c 'apk add -q curl; curl -s -m 4 -o /dev/null -w "%{http_code}\n" http://172.17.0.1:8080/'   # 200 (rule present)
docker run --rm --net=host --cap-add NET_ADMIN alpine sh -c 'apk add -q iptables >/dev/null; iptables -t nat -D POSTROUTING -s 172.17.0.2/32 -d 172.17.0.2/32 -p tcp -m tcp --dport 80 -j MASQUERADE'
docker exec natlab curl -s -m 4 -o /dev/null -w "%{http_code}\n" http://172.17.0.1:8080/   # 000, exit 28 (timeout)
docker run --rm --net=host --cap-add NET_ADMIN alpine sh -c 'apk add -q iptables >/dev/null; iptables -t nat -A POSTROUTING -s 172.17.0.2/32 -d 172.17.0.2/32 -p tcp -m tcp --dport 80 -j MASQUERADE'   # restore
docker exec natlab curl -s -m 4 -o /dev/null -w "%{http_code}\n" http://172.17.0.1:8080/   # 200 again

4. Capture a real DHCP DORA exchange.

bash
docker network create --subnet 10.99.0.0/24 dhcplab
docker run -d --name dhcpd --network dhcplab --ip 10.99.0.2 --cap-add NET_ADMIN alpine sh -c \
 'apk add -q dnsmasq tcpdump; dnsmasq -k --interface=eth0 --bind-interfaces --port=0 \
  --dhcp-range=10.99.0.100,10.99.0.150,255.255.255.0,2m --dhcp-option=option:router,10.99.0.1 \
  --dhcp-option=option:dns-server,10.99.0.53 --dhcp-option=option:domain-name,lab.test --log-dhcp'
docker exec -d dhcpd sh -c 'tcpdump -l -n -v -i eth0 "udp port 67 or udp port 68" > /tmp/dora.txt 2>&1'
docker run --rm --network dhcplab --cap-add NET_ADMIN alpine udhcpc -i eth0 -f -n -q -v
# udhcpc: broadcasting discover ... lease of 10.99.0.150 obtained from 10.99.0.2, lease time 120
docker exec dhcpd cat /tmp/dora.txt
docker rm -f dhcpd; docker network rm dhcplab

5. See what your app sees behind a proxy (Go, no Docker):

bash
cd docs/snippets/foundations/nat-dhcp-port-forwarding/go
go run ./realip          # right-to-left X-Forwarded-For with trusted CIDRs
go run ./proxyproto      # PROXY v1 from a trusted peer
go run ./patable         # the toy translation table, port exhaustion included

6. Is a forward reachable from the internet? Run from a phone hotspot or VPS: nc -vz YOUR_PUBLIC_IP 8080 or php artisan net:check-port YOUR_PUBLIC_IP 8080. "Connection refused" means a host answered with a reset (the forward works, nothing listens); a timeout means a drop (NAT, firewall or CGNAT). Compare your router's WAN address with the address curl https://ifconfig.me prints; if they differ, or the WAN address is in 100.64.0.0/10, you are behind CGNAT. Clean up: docker rm -f natlab.

Common bugs ​

SymptomCauseCheckFix
Port forward works from my phone but not from inside the LANNo hairpin NAT (NAT loopback)Does a LAN host reach the public IP?Split-horizon DNS or enable NAT reflection
Container cannot reach itself via the host portHairpin DNAT without masqueradeiptables -t nat -S; curl exit 28Use the service name, host.docker.internal, or restore Docker's rule
Port forward works at the router but not from outside at allCGNAT / double NAT; ISP blocks the port; wrong WAN IPRouter WAN IP in 100.64/10 or privateTunnel, bridge mode, ISP public IP, IPv6
Service sees one client IP for everyoneNAT/LB without TrustProxies or PROXY protocol$request->ips(), REMOTE_ADDRTrust the proxy CIDR; externalTrafficPolicy: Local
Client IP is spoofableReading the leftmost X-Forwarded-ForSend a forged headerWalk right-to-left, trust only own proxies
Intermittent timeouts under load, no refusalsconntrack table fulldmesg "table full, dropping packet", conntrack -C vs maxRaise nf_conntrack_max; reuse connections
Long idle connection (SSH, DB, WebSocket) diesNAT idle timeoutWorks while activeKeepalive below the NAT timeout
WireGuard works only if the laptop sends firstNo keepalive; NAT row expiredwg show latest handshakePersistentKeepalive = 25
VoIP has one-way audioSIP ALG rewriting SDPDisable SIP ALGSTUN/ICE, SBC
App stops working after reboot, config had a private IPDHCP lease changedip addr differsReservation, static IP outside pool, DNS name
Two hosts with the same IPStatic IP inside DHCP poolARP conflict messagesExclude it from the pool
Devices get a wrong gateway/DNSRogue DHCP serverCapture DHCP replies, nmap --script broadcast-dhcp-discoverDHCP snooping, remove the rogue box
Pod sees node IP as clientexternalTrafficPolicy: Cluster SNATApp logsSwitch to Local or use the ingress header
NAT gateway bill explodesPer-GB processing on traffic to AWS/SaaSCost explorer by usage typeVPC endpoints, caching
Webhook never arrivesReceiver behind NATNothing inboundTunnel, public endpoint

Common misconceptions ​

BeliefReality
"NAT is a firewall"It drops unsolicited inbound only as a side effect; no policy, no outbound control
"NAT hides my identity"The shared IP still identifies your site; cookies, TLS fingerprints and logs do the rest
"Port forwarding is all I need to host at home"CGNAT and double NAT make it impossible without a tunnel or a public IP
"-p 8080:80 makes the container listen on 8080"It installs a DNAT rule (and sometimes docker-proxy); the container only listens on 80
"X-Forwarded-For is the client IP"It is a list; only the entries added by trusted proxies count
"More conntrack entries is harmless"The table has a hard cap; at the cap new connections are dropped silently
"UDP has no connections, so NAT ignores it"NAT creates a row per UDP flow and expires it quickly; keepalives matter
"Hairpin works if the forward works"They are separate features
"DHCP assigns the IP forever"It is a lease with T1/T2 timers
"Docker uses DHCP for container IPs"Docker's own IPAM assigns them
"IPv6 is NAT-free so everything is reachable"A stateful firewall is still needed; global addresses are reachable by default
"A reservation equals a static IP"A reservation is server-side; a static IP is host-side and can collide
"NAT breaks only old protocols"It also affects P2P, VoIP, gaming, IPsec without NAT-T, and anything keyed on client IP

Cheat sheet ​

TopicWhat to remember
PATMany private to one public IP; the table keys on (proto, ip, port); about 64k ports per IP
SNAT vs DNATSNAT in POSTROUTING rewrites the source; DNAT in PREROUTING rewrites the destination
MasqueradeSNAT that follows the interface's current address
conntrackconntrack -L, -C, -S; limit nf_conntrack_max; established TCP timeout 5 days
Reply pathLooked up by the table; no row = dropped
Port forwardDNAT + FORWARD accept + ip_forward=1; test from outside
docker run -pDNAT rule in DOCKER chain + masquerade + hairpin rule + sometimes docker-proxy
HairpinNeeds DNAT and SNAT; fix with split DNS
CGNAT100.64.0.0/10 (RFC 6598); no inbound; tunnel or IPv6
TraversalSTUN finds the public ip:port, TURN relays, ICE chooses; symmetric NAT needs a relay
KeepaliveWireGuard PersistentKeepalive = 25; keepalive < NAT timeout
KubernetesPod egress SNAT to node; externalTrafficPolicy: Local keeps client IP
CloudNAT gateway for outbound, Internet gateway 1:1 NAT; watch per-GB cost
Client IPTrustProxies / right-to-left XFF; PROXY protocol with trusted peers only
DHCPDORA over UDP 67/68; T1 = 50%, T2 = 87.5%; options only if requested
Debugiptables -t nat -S, nft list ruleset, conntrack -L, ipconfig getpacket en0

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why does a home router need a translation table, and what happens to an inbound packet with no row? Must-know ​

Answer

Answer: The router can only undo a rewrite if it remembers it. The table maps the public port back to the private ip:port. A packet with no row cannot be delivered anywhere, so it is dropped, which is why unsolicited inbound traffic fails without a port forward.

2 — What is the difference between SNAT, masquerade and DNAT, and which chain does each use? Must-know ​

Answer

Answer: SNAT rewrites the source in POSTROUTING; masquerade is SNAT that takes the outgoing interface's current address (for dynamic WAN IPs); DNAT rewrites the destination in PREROUTING (or OUTPUT for local processes).

3 — In conntrack -L output, what do the two src= dst= sport= dport= groups mean? Important ​

Answer

Answer: The first is the original direction as the client sent it; the second is the expected reply direction after NAT. For a DNAT the second tuple shows the translated backend address.

4 — What happens when nf_conntrack_max is reached, and how would you notice? Important ​

Answer

Answer: New flows are dropped (the SYN vanishes, the client times out; no refusal). The kernel logs "table full, dropping packet"; conntrack -C is near the max and conntrack -S shows drop or insert_failed. Raise the limit, shorten timeouts, reuse connections.

5 — A container cannot reach http://host-ip:8080, its own published port, but others can. Why, and what is the fix? Important ​

Answer

Answer: Hairpin: the packet is DNATed back to the same container without source rewriting, so the reply never matches the connection. Docker adds a /32 masquerade rule to cover it; in setups without it, use the service name or fix the rule.

6 — Your router's WAN IP is 100.72.4.9. Does port forwarding work? Important ​

Answer

Answer: No. 100.64.0.0/10 is the CGNAT shared address space (RFC 6598); the ISP's NAT owns the public address and has no row for inbound packets. Use an outbound tunnel, ask for a public IP or use IPv6.

7 — Why does WireGuard need PersistentKeepalive behind NAT? Important ​

Answer

Answer: WireGuard sends nothing when idle, so the NAT row expires (often in 30 to 60 seconds for UDP) and inbound packets stop arriving. A keepalive every 25 seconds keeps the mapping alive.

8 — How do you read the real client IP from X-Forwarded-For safely? Must-know ​

Answer

Answer: Only trust the header if the TCP peer is a trusted proxy; then walk the list from the right, skipping trusted proxy addresses, and take the first untrusted address. Never take the leftmost entry.

9 — What does externalTrafficPolicy: Local change, and what is the downside? Important ​

Answer

Answer: kube-proxy only forwards to pods on the same node, which preserves the client source IP (no SNAT). Nodes without a local pod drop traffic and load can be uneven.

10 — Name the four DHCP messages, their ports and when T1 and T2 happen. Good to know ​

Answer

Answer: Discover, Offer, Request, Acknowledge over UDP (client 68, server 67). T1 is 50% of the lease (unicast renew), T2 is 87.5% (broadcast rebind); at 100% the address is dropped.

11 — Why did the lab's DHCP client not get the MTU the server was configured with? Good to know ​

Answer

Answer: DHCP servers send options the client asked for in its parameter request list (option 55). The client did not request option 26 (interface MTU), so the server did not include it.

12 — Why verify a webhook signature instead of trusting the source IP when using a tunnel? Must-know ​

Answer

Answer: Behind a tunnel the TCP peer is the tunnel agent, the public URL can be hit by anyone, and CGNAT/proxies blur the origin. An HMAC signature proves the payload came from the provider.

Glossary ​

TermMeaning
NATNetwork Address Translation: rewriting IP addresses in packet headers
NAPT / PATNAT that also rewrites ports so many hosts share one IP
MasqueradeLinux SNAT that uses the outgoing interface's current IP
SNATSource NAT: rewrite the source address, in POSTROUTING
DNATDestination NAT: rewrite the destination, in PREROUTING
Static NAT / 1:1 NATFixed one-to-one address mapping
Dynamic NATPool of public addresses handed out on demand
Port forwardingA standing DNAT rule for inbound traffic
Translation tableThe NAT's memory of rewritten flows
conntrackLinux connection tracking (netfilter)
5-tupleProtocol, source IP, source port, destination IP, destination port
Hairpin NAT / NAT loopback / NAT reflectionInside client reaching an inside server by its public address
Double NATTwo NAT devices in series
CGNAT / CGNCarrier-grade NAT done by the ISP
Shared Address Space100.64.0.0/10, RFC 6598
ALGApplication Layer Gateway: NAT code that rewrites payload addresses
STUNProtocol to learn your public ip:port
TURNRelay server for peers that cannot connect directly
ICEFramework that tries host, reflexive and relayed candidates
Hole punchingBoth peers send at once so each NAT opens a row
Symmetric NATNAT with a different external port per destination
KeepalivePeriodic packet that keeps a NAT row alive
PROXY protocolHeader a proxy prepends to pass the original client address
X-Forwarded-ForHTTP header listing the client and proxy chain
TrustProxiesLaravel middleware that trusts forwarded headers from listed proxies
externalTrafficPolicyKubernetes Service field; Local preserves the client IP
NAT gatewayManaged cloud outbound NAT
Internet gatewayCloud component doing 1:1 NAT for public addresses
Elastic IPAWS static public IPv4 address
DHCPDynamic Host Configuration Protocol
DORADiscover, Offer, Request, Acknowledge
LeaseTime-limited right to use an address
T1 / T2Renewal (50%) and rebinding (87.5%) timers
ReservationServer-side fixed address for a MAC/client ID
Relay agentForwards DHCP broadcasts across subnets (giaddr, option 82)
Rogue DHCPUnauthorised DHCP server
DHCP snoopingSwitch feature that only allows DHCP replies from trusted ports
DHCPv6Stateful IPv6 configuration (UDP 546/547)
SLAACStateless Address Autoconfiguration from Router Advertisements
Ephemeral portShort-lived source port for client connections
Magic cookie63 82 53 63 marking DHCP options in a BOOTP packet

References ​

Every URL was fetched and its text saved under scratchpad/sources/nat-dhcp-port-forwarding/; the HTTP status was 200 when fetched.

Built by Morteza Negahi