Docker Port Mapping and NAT with iptables: A Comprehensive Guide
This guide explains how Docker uses -p and -P options for port mapping, how to bind specific host IPs and protocols, view mappings, combine multiple bindings, and expose un‑mapped containers later via host iptables NAT rules for full network access.
Docker allows exposing container services externally or inter‑container communication via port mapping using the -p or -P options.
Only one host port can map to a single container port, but a container port can be mapped from multiple host ports (e.g., 8080→80, 8090→80, 8099→80).
Using -p you specify an explicit host port, for example docker run -ti -d --name my-nginx -p 8088:80 docker.io/nginx . Using -P Docker assigns a random host port, e.g., docker run -ti -d --name my-nginx2 -P docker.io/nginx . The resulting docker ps output shows the mappings.
You can bind a specific host IP address together with a port, for example docker run -ti -d --name my-nginx3 -p 127.0.0.1:8888:80 docker.io/nginx or docker run -ti -d --name my-nginx4 -p 192.168.210.100:9999:80 docker.io/nginx . Access is limited to the bound IP.
Port mapping can also specify a protocol, such as docker run -ti -d --name my-nginx5 -p 8099:80/tcp docker.io/nginx or docker run -ti -d --name my-nginx6 -p 192.168.210.100:8077:80/udp docker.io/nginx .
To view a container’s current bindings, use docker port CONTAINER or inspect the container JSON for the IPAddress field.
Multiple -p options can bind several host IP/port pairs to the same container port, e.g., docker run -ti -d --name my-nginx8 -p 192.168.210.100:7777:80 -p 127.0.0.1:7788:80 docker.io/nginx .
If a container is started without any port mapping, you can expose it later with host iptables NAT rules. After obtaining the container’s IP (e.g., 172.17.0.2 ), add rules such as:
iptables -t nat -A PREROUTING -p tcp --dport 9998 -j DNAT --to-destination 172.17.0.2:80
iptables -t nat -A POSTROUTING -d 172.17.0.2/32 -p tcp --sport 80 -j SNAT --to-source 192.168.210.100
iptables -t filter -A INPUT -p tcp --dport 9998 -m state --state NEW -j ACCEPT
Save the rules with iptables-save > /etc/sysconfig/iptables , ensure the icmp-host-prohibited lines are commented out, restart the iptables service, and the host port (e.g., http://192.168.210.100:9998/ ) will forward to the container’s port 80.
Practical DevOps Architecture
Hands‑on DevOps operations using Docker, K8s, Jenkins, and Ansible—empowering ops professionals to grow together through sharing, discussion, knowledge consolidation, and continuous improvement.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.