Skip to main content

Port Publishing

Port publishing maps a container port to a host port with -p or ports in Compose, making a container service reachable from outside. Docker implements it with iptables NAT rules.

What it does

A container's ports are private to its network by default. Publishing creates a forwarding rule, so traffic to a host port is redirected to the container's IP and port. EXPOSE in a Dockerfile only documents a port and publishes nothing.

Syntax

Bash
docker run -d -p 8080:80 nginx:1.27 # host 8080 -> container 80
docker run -d -p 127.0.0.1:9090:9090 prometheus # localhost only
docker run -d -P nginx:1.27 # random host ports for EXPOSEd ports
docker run -d -p 53:53/udp dns-server # UDP
docker port my-nginx
YAML
services:
api:
ports:
- "8080:8080"
- "127.0.0.1:9090:9090"

How traffic flows

Bash
sudo iptables -t nat -L DOCKER -n --line-numbers
# DNAT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:8080 to:172.17.0.2:80

Docker adds these rules itself, and they can bypass host firewall tools such as ufw, so published ports may be reachable even if you did not intend that.

Binding scope

By default -p 8080:80 binds to all interfaces. Bind admin, metrics, and database ports to 127.0.0.1 unless remote access is required.

Common Mistake

Thinking EXPOSE makes a container reachable. Publish with -p or ports.

Security

Published ports are exposed to everything that can reach the host. Review docker ps for 0.0.0.0 bindings before going live.

Frequently Asked Questions

What is the difference between EXPOSE and -p?

EXPOSE is documentation of the port the app listens on. Only -p, or -P with exposed ports, creates the NAT rule that makes the port reachable from the host and beyond.

Why can't two containers publish the same host port?

A host port can be bound by only one listener, so the second container fails to start. Map different host ports or put a reverse proxy in front.

Does ufw block Docker published ports?

Not reliably. Docker manages iptables rules directly, so published ports can bypass ufw rules. Bind to 127.0.0.1 or use Docker-aware firewall rules.

Found a mistake, an outdated step or a broken link?