Card 03/ 06
Port Order in docker run -p
The container runs, docker ps looks right, and the browser still cannot connect.
-p publishes a container's port on your machine, so that a program running inside the container (an isolated process started from an image) can be reached from outside it, and it takes two numbers in a fixed order: the port on your machine first, the port inside the container second. Writing them the wrong way round is one of the most common Docker mistakes, and it fails in a way that looks like something else.
The container is running, docker ps lists it, and the browser says the connection was refused. Nothing is broken; the two numbers are swapped:
docker run -d -p 80:8080 nginx
curl localhost:8080
curl: (7) Failed to connect to localhost port 8080 after 0 ms: Couldn't connect to server-p reads host first, container second. The command above asked the host to listen on 80 and forward to port 8080 inside the container, where nothing is listening, because nginx serves on 80.
-p 8080:80 | Means |
|---|---|
8080 | The port on your machine. This is the one you type in the browser |
80 | The port the program inside the container is listening on |
Reversed, the mistake fails quietly: the host really does open the port you named, so docker ps looks correct and only the connection fails.
So when a published container refuses connections, read the -p pair first. The number on the right must be the port the program inside listens on, which the image's documentation states.
← → move through sections and cards