-p HOST:CONTAINER exists for traffic that comes from outside Docker: a browser, curl on the host, another machine. Containers on the same network do not need it. They connect to each other's IPs and ports directly.
host / outside world
│ -p 8080:80 (only published port)
▼
┌─ shop network ───────────────────────────────────┐
│ web :80 ──► api :3000 ──► db :6379 │
│ published not published not published │
└──────────────────────────────────────────────────┘| Traffic | Needs -p? |
|---|---|
Browser or host curl → web | yes |
web → api:3000 on the same network | no |
api → db:6379 on the same network | no |
Host curl → db | only if published, and it should not be |
Publish only the entry point
docker run -d --name db --network shop redis:7.4
docker run -d --name api --network shop -e HOST=0.0.0.0 shop/inventory-api:1.0
docker run -d --name web --network shop -p 8080:80 -v ~/shop/nginx:/etc/nginx/conf.d:ro nginx:1.27The host reaches web but not db:
curl -s localhost:8080inventory-api: 42 items in stock (request 1)curl localhost:6379curl: (7) Failed to connect to localhost port 6379 after 0 ms: Couldn't connect to serverdocker ps shows the difference in the PORTS column: 0.0.0.0:8080->80/tcp is published, a bare 6379/tcp is only reachable on the network.
The service must listen on 0.0.0.0
Reaching a port without publishing it only works if the program accepts connections on the container's network IP. Many frameworks bind 127.0.0.1 by default:
| Bind address | Who can connect |
|---|---|
127.0.0.1 | Only processes inside the same container |
0.0.0.0 | Anything that can reach the container's IPs |
The log usually shows it:
docker logs apiinventory-api listening on 127.0.0.1:3000 (redis at db:6379)From inside the container it works, from web it does not:
docker exec api wget -qO- localhost:3000
docker exec web curl -s api:3000The first prints the response. The second fails with exit code 7 (connection refused). Change the bind address through the app's setting (here HOST=0.0.0.0, elsewhere --host 0.0.0.0 or a config file) and recreate the container.