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
docker run -d -p 8080:80 nginx:1.27 # host 8080 -> container 80docker run -d -p 127.0.0.1:9090:9090 prometheus # localhost onlydocker run -d -P nginx:1.27 # random host ports for EXPOSEd portsdocker run -d -p 53:53/udp dns-server # UDPdocker port my-nginxservices: api: ports: - "8080:8080" - "127.0.0.1:9090:9090"How traffic flows
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:80Docker 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 MistakeThinking
EXPOSEmakes a container reachable. Publish with-porports.
SecurityPublished ports are exposed to everything that can reach the host. Review
docker psfor0.0.0.0bindings 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.