Skip to main content
In this lesson, we’ll explore how Docker publishes container ports to the host system. We begin with basic port mapping, then move on to advanced options like interface binding, dynamic port allocation, and automatic exposure. By the end, you’ll understand how Docker leverages iptables to route traffic between host and container.

1. Container vs Host IP

A containerized web application typically listens on an internal port (e.g., 5000). Every container receives an internal IP (for example, 172.17.0.2), which is only reachable from the Docker host:
However, this IP isn’t accessible from other machines. To allow external access, you must map the container port to a port on the host (e.g., 192.168.1.5).

2. Publishing a Fixed Port (-p)

To map container port 5000 to host port 80, run:
Now your application is accessible at:

Multiple Instances on Different Ports

You can launch multiple containers binding the same internal port to different host ports:
For database services:
Host ports must be unique. Attempting to bind the same host port twice will cause Docker to error out.

3. Binding to Specific Host Interfaces

If your machine has multiple network interfaces, you can restrict port binding to a particular IP:

4. Dynamic Host Port Allocation

Omitting the host port lets Docker assign a random port (default range 32768–60999):
To view the port range:

5. Publishing All Exposed Ports (-P)

If an image’s Dockerfile declares one or more EXPOSE ports, you can automatically map them to random host ports:
Build and run:
You can also expose additional ports at runtime:
Inspect the exposed ports:

6. Port Publishing Options at a Glance

7. Under the Hood: iptables NAT

Docker uses Linux iptables to forward traffic from host ports to container IPs. It creates custom chains (DOCKER, DOCKER-USER) in the nat table:
  1. Packet arrives on the host port.
  2. PREROUTING chain directs it to the DOCKER chain.
  3. A DNAT rule rewrites the packet’s destination to the container’s IP and port.
  4. The packet is forwarded to the container.
  5. Response packets are SNAT’d or MASQUERADE’d back to the host.
Inspect Docker’s NAT rules:
You can insert custom rules in the DOCKER-USER chain to filter or modify traffic before Docker’s own rules apply.

Further Reading and References

Watch Video