In this lesson, you will learn how to bridge the gap between your isolated container applications and the outside world using Network Address Translation (NAT) and port mapping.
The Problem: Isolation
As we’ve discussed in previous lessons, containers rely on Linux namespaces to provide strict process isolation. By default, your container lives in its own private network "bubble." If you run a web server inside a container on port 80, that service is invisible to the rest of your computer. This is excellent for security, but frustrating if you actually want to access your application.
The Solution: Port Mapping
To allow traffic to flow from your host machine into the container, we use Port Mapping. When you start a container, you can instruct Docker to create a NAT rule. This rule tells the host: "Any traffic arriving at port 8080 on my laptop should be translated and forwarded to port 80 inside the container."
This mapping acts as a secure gateway. The container remains isolated, unaware of the host’s internal network, while the host acts as a traffic controller, directing authorized packets into the container's private namespace.
How it looks
When you launch a container, you use the -p flag to define this mapping. Consider this example:
docker run -p 8080:80 nginx
In this command:
8080is the port on your host machine.80is the port inside the container.
When a user visits http://localhost:8080 in their browser, the Docker daemon intercepts that traffic using NAT rules configured in the Linux kernel. It translates the destination IP and port to route the packet directly to the container’s virtual Ethernet interface. The container processes the request on its internal port 80 and sends the response back through the same NAT translation, keeping the internal environment completely sealed off from the host’s broader network configurations.
Key Takeaway: Port mapping uses NAT to safely expose specific, granular internal container services to the host network without breaking the security boundaries of the container's isolated namespace.