Networkingeasy0-2 years

A Spring Boot container is configured with `SPRING_DATASOURCE_URL=jdbc:postgresql://localhost:5432/orders`, and the database is a sibling container in the same Compose file. The application can't connect. Why not, and what should the URL say instead?

localhost inside a container refers to that container itself, not the host machine and not any sibling container — each container gets its own network namespace, and localhost inside it resolves to that namespace's own loopback interface. The Postgres container is a completely separate process in a completely separate namespace; nothing is listening on port 5432 inside the application's container, so the connection is refused. On a Docker user-defined network (which Compose creates by default for a project), every container can reach every other by its service name as a hostname — Docker runs an embedded DNS server that resolves it — so the URL should read jdbc:postgresql://postgres:5432/orders, using the Compose service name, not localhost and not the container's own name from outside.

The lesson behind it →