Notes
Filed under · Docker · 2026-07-31 · 5 min read
Why localhost stops working inside Docker
This confused me the first time I connected an API container to a database container. My application used localhost:5432. PostgreSQL was running, but the API could not connect.
Inside a Docker container, localhost refers to that same container. It does not automatically mean your laptop or another container.
A Compose example
yamlservices:
api:
build: .
ports:
- "3000:3000"
environment:
DATABASE_URL: postgres://app:password@db:5432/app
depends_on:
- db
db:
image: postgres:17
environment:
POSTGRES_USER: app
POSTGRES_PASSWORD: password
POSTGRES_DB: appNotice @db:5432. "db" is the Compose service name. Containers on the same Compose network can normally reach that service using its service name. Using localhost:5432 from the API container would point back to the API container itself.
Host machine vs container
If I open the application from my normal browser, I might use http://localhost:3000 because Docker maps the container port to my host. But container-to-container communication uses the Docker network.
From your laptop, localhost means your laptop. From a container, localhost means that container.