Course contentsShow
← Linux
Lesson 1510 of 1,81913. Containerization Primitives and NamespacesFree lesson

Network Address Translation (NAT)

Configure source and destination NAT rules to allow containers to access external networks.

In this lesson, you will learn how to configure Source NAT (SNAT) and Destination NAT (DNAT) using iptables to enable network connectivity for containers isolated within network namespaces.

The Role of NAT in Container Networking

Containers typically reside in their own private network namespaces with IP addresses that are not routable from the outside world. To allow them to talk to the internet (or other hosts), we must perform Network Address Translation (NAT) at the host level, where the host acts as a gateway.

Configuring Source NAT (SNAT/Masquerade)

When a container initiates an outbound request, the packet leaves the container with a private source IP. Before it hits the external network, the host must replace that private IP with its own public IP. In Linux, we use the MASQUERADE target, which automatically selects the primary IP of the host’s outgoing interface:

# Allow traffic from the container's bridge (e.g., veth-bridge) to be masqueraded
iptables -t nat -A POSTROUTING -s 172.17.0.0/16 -o eth0 -j MASQUERADE

The POSTROUTING hook is critical here; it ensures the translation happens after the routing decision, right before the packet leaves the physical interface.

Configuring Destination NAT (DNAT)

Conversely, if you want external clients to reach a service running inside a container, you must map a host port to the container’s internal IP. This requires DNAT in the PREROUTING chain, which inspects packets as they arrive on the host before they are routed:

# Forward incoming traffic on host port 8080 to container IP 172.17.0.2 on port 80
iptables -t nat -A PREROUTING -p tcp --dport 8080 -j DNAT --to-destination 172.17.0.2:80

Connection Tracking (conntrack)

Because NAT modifies packet headers, the kernel must keep track of these transformations. Using the conntrack subsystem, Linux remembers the original source/destination mappings so that return traffic (the response) is automatically de-masqueraded or de-DNATed, ensuring the data correctly reaches the originating container without manual intervention for every packet.

Key Takeaway: SNAT (Masquerade) allows containers to initiate outbound communication by hiding their private IPs behind the host, while DNAT allows external traffic to reach internal containers by mapping host ports to private container addresses.