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:
192.168.1.5).
2. Publishing a Fixed Port (-p)
To map container port 5000 to host port 80, run:
Multiple Instances on Different Ports
You can launch multiple containers binding the same internal port to different host ports: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):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:
6. Port Publishing Options at a Glance
| Option | Description | Syntax |
|---|---|---|
-p | Map specific host and container ports | -p [host_ip:]host_port:container_port |
-P | Publish all EXPOSEd ports to random host ports | -P |
--expose | Expose additional container ports (no host bind) | --expose=port[/protocol] |
7. Under the Hood: iptables NAT
Docker uses Linuxiptables to forward traffic from host ports to container IPs. It creates custom chains (DOCKER, DOCKER-USER) in the nat table:
- Packet arrives on the host port.
- PREROUTING chain directs it to the
DOCKERchain. - A DNAT rule rewrites the packet’s destination to the container’s IP and port.
- The packet is forwarded to the container.
- Response packets are SNAT’d or MASQUERADE’d back to the host.
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