The neighbour's name is found. Here: which port goes next to it.
The option -p 15432:5432 publishes a port on the host: Docker listens on 15432 on the host's addresses and forwards connections into the container on 5432. It is the entrance for those who come from the host and from outside.
Neighbours on a network connect to a container directly. The name db leads to its address in the network, and the port next to it is the one the program inside listens on: 5432. A database that only neighbours talk to needs no -p at all. You publish a port on the entry container — for example, the web server users come to.
localhost in a container is the container itself: nc localhost 5432 from app connects to app, where nobody listens on port 5432.
| Where the connection comes from | Address |
|---|---|
| the host | localhost:15432 — the published port |
| a container in the same network | db:5432 — the name and the program's port |
db is started with -p 15432:5432 and shares a network of your own with app. What will sudo docker exec app nc -w 2 db 15432 print?
-
In a shared network of your own the name
dbis found. The connection fails later, at the port. -
The name leads straight to the container's address in the network, bypassing the host. A connection goes through the host when it targets a host address, such as
localhost:15432on the server itself. -
Port 15432 is listened on by Docker on the host. The name
dbleads to the container's own address, where only 5432 is listened on.
The name db leads to the container's address, and nc connects to its port 15432, where nobody listens. The published port exists only on the host. Neighbours connect to the port db itself listens on, 5432.
Key points
- A published port is listened on by Docker on the host; neighbours on the network do not need it.
- A neighbour connects by the container's name and the port the program inside listens on.
-
localhostin a container leads to the container itself.