Command Palette

Search for a command to run...

Hectal
PHASE 4Intermediate ~7 min· topic 3 of 4

Topic 4.3

NAT & PAT: Sharing Addresses

In one line

NAT rewrites addresses as packets cross a boundary; PAT (port address translation) lets thousands of private hosts share one public IP by also rewriting ports, tracking each connection in a table.

0/4 · 0%

Think of it like this

An office with one public phone number and a receptionist. Outgoing calls all show the main number; the receptionist remembers who called whom, so returning calls go back to the right extension. Nobody outside can dial an extension directly.

Key ideas

  1. 01

    SNAT/PAT (outbound): a private host 10.0.1.5:43210 talks to 93.184.216.34:443; the NAT device rewrites the source to its public IP and a free port, 203.0.113.7:61001, and records the mapping in its CONNECTION TRACKING table. Replies to 203.0.113.7:61001 are translated back. Home routers, AWS NAT gateways, and Docker's default bridge all do this.

  2. 02

    DNAT / port forwarding (inbound): traffic arriving at a public address and port is rewritten to a private destination. docker run -p 8080:80 and Kubernetes NodePort Services are implemented with DNAT rules (iptables/nftables).

  3. 03

    Limits: a NAT IP has ~64,000 source ports PER DESTINATION (IP and port). Many connections to the same busy endpoint can exhaust them (AWS reports ErrorPortAllocation on NAT gateways). NAT tables also have idle timeouts, so idle long-lived connections get silently dropped.

  4. 04

    NAT breaks end-to-end addressing: servers see the NAT's IP, not the client's. That's one reason proxies add X-Forwarded-For, and one reason IPv6 (Topic 1.4) removes the need for NAT.

Code & diagrams

nat.shbash
sudo iptables -t nat -L -n -v       # NAT rules (Docker adds MASQUERADE and DNAT entries here)
sudo conntrack -L | head            # live connection-tracking entries (install conntrack-tools)
sudo conntrack -C                   # how many tracked connections right now
cat /proc/sys/net/netfilter/nf_conntrack_max   # table size limit
Patdiagram
Rendering diagram…

Explain it without notes

01

Why can a private instance behind a NAT gateway reach the internet while nothing on the internet can start a connection to it?

Practice

01

A worker fleet behind one NAT gateway makes thousands of connections per second to one third-party API endpoint and starts seeing connection errors. What's the likely cause and two fixes?

Trade-offs

  • ↔

    NAT conserves public IPv4 addresses and gives outbound-only access cheaply, but adds per-connection state, port limits, idle timeouts, hides client identity, and costs money per GB in the cloud.

Done when you can

  • I can explain SNAT/PAT and DNAT/port forwarding.

  • I know about connection tracking tables and their limits.

  • I understand NAT port exhaustion and idle timeouts.