Every container has its own network namespace, so every container can listen on port 80. The host has one set of ports. That is the whole rule:
| Side | Unique per | Who chooses it |
|---|---|---|
| Container port | Container | The program (nginx listens on 80) |
| Host port | Host | You, with -p |
Same container port, different host ports
host :8080 ──► blue :80 nginx
host :8081 ──► green :80 nginxdocker run -d --name blue -p 8080:80 nginx:1.27
docker run -d --name green -p 8081:80 nginx:1.27A host port can be used once
docker run -d --name red -p 8080:80 nginx:1.27docker: Error response from daemon: driver failed programming external connectivity on endpoint red (f204b401e44f...): Bind for 0.0.0.0:8080 failed: port is already allocatedThe container was created but could not start. docker ps -a lists it as Created. Remove it before reusing the name:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
6df65503b990 nginx:1.27 "/docker-entrypoint.…" 2 seconds ago Created redChoose the host address
-p takes an optional host address in front:
| Flag | Host listens on | Reachable from |
|---|---|---|
-p 8082:80 | 0.0.0.0:8082 (every interface) | The host and other machines |
-p 127.0.0.1:8082:80 | 127.0.0.1:8082 | The host only |
docker run -d --name admin -p 127.0.0.1:8082:80 httpd:2.4
docker port admin80/tcp -> 127.0.0.1:8082Use 127.0.0.1 for admin pages and databases that only local tools should reach.
Let Docker pick: -P
-P (capital) publishes every port the image declares with EXPOSE, each on a free high host port:
docker run -d --name auto -P nginx:1.27
docker port auto80/tcp -> 0.0.0.0:32768Read the chosen port with docker port or docker ps. It changes each time the container is created.
Two errors, two causes
-p 8090:8080 nginx host :8090 ──► container :8080 (nginx is on :80)curl localhost:PORT prints | Cause |
|---|---|
Couldn't connect to server | No container publishes that host port |
Recv failure: Connection reset by peer | The port is published, but nothing listens on the container port it maps to |
The second error means the right side of -p is wrong. Check which port the program listens on (its docs, docker logs, or EXPOSE in docker image inspect) and recreate the container.