Publishing Ports
Each container has its own network namespace, with its own IP address and its own set of ports. A web server listening on port 80 inside a container is not reachable from your host until you publish the port: Docker then forwards traffic from a host port to the container port.
docker run -d --name web -p 8080:80 nginx:1.27
curl http://localhost:8080
docker port webSample output:
<!DOCTYPE html>
<html><head><title>Welcome to nginx!</title>...
80/tcp -> 0.0.0.0:8080
80/tcp -> [::]:8080Read -p 8080:80 as host:container, "host port 8080 goes to container port 80". Mixing up the order is the number-one port mistake.
The -p syntax
| Flag | Meaning |
|---|---|
-p 8080:80 |
host port 8080 on all interfaces → container port 80/tcp |
-p 127.0.0.1:8080:80 |
only reachable from the host itself (not from the LAN) |
-p 80 |
container port 80 → a random free host port |
-p 5353:53/udp |
UDP instead of TCP |
-p 8000-8002:8000-8002 |
a range |
-P |
publish every EXPOSEd port on random host ports |
The model parses these forms into the bindings Docker would create (random ports are handed out in order here, starting at 32768, to keep the output stable):
next_random = 32768
def parse_publish(spec):
global next_random
spec, _, proto = spec.partition("/")
proto = proto or "tcp"
parts = spec.split(":")
if len(parts) == 3:
ip, host, container = parts
elif len(parts) == 2:
ip, host, container = "0.0.0.0", parts[0], parts[1]
else:
ip, host, container = "0.0.0.0", "", parts[0]
def expand(r):
if "-" in r:
low, high = map(int, r.split("-"))
return list(range(low, high + 1))
return [int(r)]
containers = expand(container)
if host:
hosts = expand(host)
else:
hosts = list(range(next_random, next_random + len(containers)))
next_random += len(containers)
if len(hosts) != len(containers):
raise ValueError("host and container port ranges must be the same size")
return [f"{ip}:{h} -> {c}/{proto}" for h, c in zip(hosts, containers)]
for spec in ["8080:80", "127.0.0.1:5432:5432", "80", "5353:53/udp", "8000-8002:8000-8002", "443"]:
print(f"-p {spec:<22} {parse_publish(spec)}")-p 8080:80 ['0.0.0.0:8080 -> 80/tcp']
-p 127.0.0.1:5432:5432 ['127.0.0.1:5432 -> 5432/tcp']
-p 80 ['0.0.0.0:32768 -> 80/tcp']
-p 5353:53/udp ['0.0.0.0:5353 -> 53/udp']
-p 8000-8002:8000-8002 ['0.0.0.0:8000 -> 8000/tcp', '0.0.0.0:8001 -> 8001/tcp', '0.0.0.0:8002 -> 8002/tcp']
-p 443 ['0.0.0.0:32769 -> 443/tcp']
One host port, one container
Two containers can both listen on port 80 internally, since each has its own namespace. But a host port can only be bound once per IP address and protocol. The second docker run -p 8080:80 fails:
docker: Error response from daemon: driver failed programming external connectivity on endpoint web2:
Bind for 0.0.0.0:8080 failed: port is already allocated.class Host:
def __init__(self):
self.bindings = {} # (ip, port, proto) -> container
def publish(self, container, ip, host_port, container_port, proto="tcp"):
for (bound_ip, port, bound_proto), owner in self.bindings.items():
same_port = (port, bound_proto) == (host_port, proto)
overlaps = bound_ip == ip or "0.0.0.0" in (bound_ip, ip)
if same_port and overlaps:
print(f"{container}: Bind for {ip}:{host_port} failed: port is already allocated (by {owner})")
return
self.bindings[(ip, host_port, proto)] = container
print(f"{container}: {ip}:{host_port}/{proto} -> container port {container_port}")
host = Host()
host.publish("web1", "0.0.0.0", 8080, 80)
host.publish("web2", "0.0.0.0", 8081, 80) # same container port, different host port: fine
host.publish("web3", "0.0.0.0", 8080, 80) # clash
host.publish("dns", "0.0.0.0", 8080, 53, "udp") # UDP is a separate port space
host.publish("admin", "127.0.0.1", 8080, 80) # 0.0.0.0 already covers 127.0.0.1
host.publish("db", "127.0.0.1", 5432, 5432)web1: 0.0.0.0:8080/tcp -> container port 80
web2: 0.0.0.0:8081/tcp -> container port 80
web3: Bind for 0.0.0.0:8080 failed: port is already allocated (by web1)
dns: 0.0.0.0:8080/udp -> container port 53
admin: Bind for 127.0.0.1:8080 failed: port is already allocated (by web1)
db: 127.0.0.1:5432/tcp -> container port 5432
The app must listen on 0.0.0.0
A classic puzzle: the container runs, the port is published, but curl localhost:8080 gets "connection reset". Usually the app inside listens on 127.0.0.1, which inside the container means the container's own loopback. Docker's forwarded traffic arrives on the container's network interface (e.g. 172.17.0.2), so the app never sees it.
| App binds to | Reachable through -p? |
|---|---|
127.0.0.1:8000 (Flask's and Vite's default) |
no |
0.0.0.0:8000 |
yes |
flask run --host 0.0.0.0 --port 8000
python -m http.server 8000 --bind 0.0.0.0
npx vite --host 0.0.0.0Security note
-p 5432:5432 publishes your database on every network interface of the host. On a laptop on public Wi-Fi, or a cloud VM, that can expose it to the world. Docker also inserts its own firewall (iptables) rules, which can bypass host firewalls such as ufw. For services only you need to reach, bind to localhost:
docker run -d -p 127.0.0.1:5432:5432 -e POSTGRES_PASSWORD=dev postgres:17Containers that only talk to each other (an app and its database) don't need published ports at all: put them on the same user-defined network (see Networks).
Test yourself
In docker run -p 3000:8080 api, which port does the app inside the container listen on?
- 3000
- 8080
- Both
- A random port
The port is published, but requests fail. The app inside logs Listening on 127.0.0.1:8000. What's wrong?
- The image is too old
- The app only listens on the container's loopback; it must listen on 0.0.0.0
- Port 8000 is reserved
- You need EXPOSE 8000
How do you publish a database port so it's reachable only from the host machine?
- -p 5432
- -p 5432:5432
- -p 127.0.0.1:5432:5432
- --expose 5432