Inside my container, connecting to localhost:5432 fails with "connection refused", though the database works fine from my laptop terminal. How do I reach a service running on the host or in another container?
#docker#networking#troubleshooting
DEV3 Developer Forum
Every post is reviewed first. Usually reviewed within 24 hours.
Inside my container, connecting to localhost:5432 fails with "connection refused", though the database works fine from my laptop terminal. How do I reach a service running on the host or in another container?
#docker#networking#troubleshooting
Inside a container, localhost means the container itself. Each container has its own network namespace, so the host's services and other containers are not on it.
Another container in the same Compose project: use the service name.
services:
app:
environment:
DATABASE_URL: postgres://user:pass@db:5432/app
db:
image: postgres:17
Compose creates a default network where service names resolve through DNS. Use the container port (5432), not a published host port. Services started with plain docker run need a user-defined network (docker network create appnet, then --network appnet) for name resolution.
A service on the host machine
host.docker.internal.services:
app:
extra_hosts:
- "host.docker.internal:host-gateway"
Then connect to host.docker.internal:5432. (The older route is the bridge gateway IP, commonly 172.17.0.1.)
127.0.0.1, set listen_addresses / bind-address to include the Docker bridge interface, and allow it in pg_hba.conf and the firewall. This exposes the service to more interfaces, so restrict by firewall.network_mode: host (works natively on Linux) shares the host network, so localhost works, but it disables port isolation and port mappings.From the host to a container: publish a port (ports: ["5432:5432"]) and connect to localhost:5432. Bind to 127.0.0.1:5432:5432 to keep it private.
Debug steps
docker compose exec app sh
getent hosts db # does the name resolve?
nc -zv db 5432 # is the port open?
docker network inspect <project>_default
Also check that the database has finished starting (healthchecks, see the Compose topic) and that credentials and database names match.