Docker Compose Connection Refused: localhost vs Service DNS
localhost inside a container is that container. Compose resolves service names on a shared network, depends_on does not wait for readiness, and binding loopback breaks the rest.

Introduction & Quick Summary
Symptom. docker compose up starts an API and a database, and the API exits with Error: connect ECONNREFUSED 127.0.0.1:5432 or dial tcp [::1]:5432: connect: connection refused. The identical DATABASE_URL works when you run the API with npm run dev on the host. Sometimes the service starts and fails minutes later on the first request, or a second container cannot reach the first at all.
Cause. Every container has its own network namespace with its own loopback interface, so localhost inside the API container means "this container", not the host and not the database. Compose gives each service a DNS name on a shared network — the service name — and that name is the only stable address between containers. Two secondary causes look like the same error: depends_on waits for the container to start, not for the database to accept connections, and a server configured to listen on 127.0.0.1 inside its own container accepts nothing from the network even when the address is right.
Fix. Use the service name and internal port (db:5432), not the published host port. Add a healthcheck to the database and gate the app with depends_on: condition: service_healthy. Make the server bind 0.0.0.0 inside its container, and reach the host from a container via host.docker.internal (or host-gateway on Linux) rather than localhost.
Core Mechanics, Signatures & Reproducible Setup
A compose file that reproduces both failures:
services:
api:
build: .
environment:
DATABASE_URL: postgres://app:secret@localhost:5432/app # wrong: its own loopback
ports:
- "3000:3000"
depends_on:
- db
db:
image: postgres:17-alpine
environment:
POSTGRES_USER: app
POSTGRES_PASSWORD: secret
POSTGRES_DB: app
ports:
- "5432:5432"The corrected version:
services:
api:
build: .
environment:
DATABASE_URL: postgres://app:secret@db:5432/app # service name, internal port
HOST: 0.0.0.0
PORT: 3000
ports:
- "3000:3000" # host -> container only
depends_on:
db:
condition: service_healthy
healthcheck:
test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:3000/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"]
interval: 10s
timeout: 3s
retries: 5
db:
image: postgres:17-alpine
environment:
POSTGRES_USER: app
POSTGRES_PASSWORD: secret
POSTGRES_DB: app
healthcheck:
test: ["CMD-SHELL", "pg_isready -U app -d app"]
interval: 5s
timeout: 3s
retries: 10
start_period: 10sdepends_on with a long-form condition is Compose v2 behaviour; the short list form only orders container creation. service_healthy requires a healthcheck on the dependency, and start_period is what stops a slow first boot from counting as failures.
Prove the address before touching application code:
docker compose exec api getent hosts db
docker compose exec api sh -lc 'curl -sv telnet://db:5432 --max-time 3 | head'
docker compose exec db pg_isready -U app -d appgetent hosts db prints the container IP if DNS works; curl with telnet:// reports whether the port answers. Testing with the cURL builder in the same container removes the application entirely from the question.
Key Comparison Table
| From → To | Address to use | Why |
|---|---|---|
| container → container | service-name:internal-port | Compose DNS on the shared network |
| host → container | localhost:published-port | Port mapping on the host's interface |
| container → host | host.docker.internal:port | Docker Desktop; needs host-gateway on Linux |
| container → itself | 127.0.0.1:port | Only if the server binds 0.0.0.0 or loopback |
| container → internet | normal DNS | Bridge network with NAT |
| Startup control | Waits for | Use for |
|---|---|---|
depends_on: [db] | Container created | Nothing about readiness |
condition: service_started | Process started | Same weakness as above |
condition: service_healthy | Healthcheck passing | Databases, brokers, migrations |
restart: on-failure + retry in app | First successful connection | Robust option in production |
docker compose up --wait | All healthchecks green | CI and local boot scripts |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. The published port is not the internal port
ports: ["5433:5432"] publishes 5433 on the host and leaves 5432 inside the container network. An app container must still use db:5432; only host tools use localhost:5433. Mixing them produces a connection refused on a port that "obviously" works — from your laptop, in another terminal.
2. A server that only listens on loopback
Postgres images listen on all interfaces by default, but application servers and some databases do not. A Node app started as app.listen(3000, 'localhost'), or a Python server with --host 127.0.0.1, is unreachable from another container and from the host port mapping, even though docker compose exec works:
// broken inside a container
server.listen(3000, 'localhost');
// correct
server.listen(3000, '0.0.0.0');The same class of bug appears with images whose default config binds loopback: Redis (bind 127.0.0.1 in a copied config), MySQL (--bind-address=127.0.0.1), and several JVM apps.
3. Node resolves localhost to ::1 first
Node 17 changed dns.lookup ordering to follow the system resolver, which prefers IPv6. A server listening on 127.0.0.1 only, reached as localhost, gives ECONNREFUSED ::1:5432 — a different address than the one in the error you expected. Use the explicit address, or make the server listen on both:
import net from 'node:net';
net.createServer().listen({ host: '::', port: 3000, ipv6Only: false });4. Reaching a service on the host from a container
For a database running outside Docker, localhost inside the container is still wrong. On Docker Desktop, host.docker.internal resolves automatically; on Linux it must be declared:
services:
api:
extra_hosts:
- "host.docker.internal:host-gateway"Then use host.docker.internal:5432. The on-host server must also listen on 0.0.0.0 (or the Docker bridge address) and allow the container's subnet in pg_hba.conf.
5. container_name and DNS aliases
Compose's DNS records the service name and any networks.aliases. Setting container_name does not create a DNS entry for that name on all platforms, and two projects that both define a db service are isolated by project-scoped networks, so db resolves inside the project only.
services:
api:
networks: [backend]
db:
networks:
backend:
aliases: [postgres, primary]
networks:
backend:6. Connections that succeed at boot and fail later
A pool created at import time connects before the database is ready, retries with backoff, then dies on the first query with Connection terminated unexpectedly. Compose restarts the container, and the log shows a successful start followed by a crash three minutes later. Gate startup on readiness and let the pool reconnect:
const pool = new Pool({ connectionString: url, max: 10, connectionTimeoutMillis: 5000 });
pool.on('error', (err) => log.warn({ err }, 'idle client error')); // never throw hereCommon Compilation/Runtime Mistakes & Version Gotchas
version:in the compose file. Obsolete since Compose v2 and now a warning; the schema follows the file, not the key.links. Legacy Docker networking that still works but bypasses service discovery rules and hides aliases; use networks and service names.exposevsports.exposedocuments an internal port and publishes nothing;portsmaps to the host. Neither is required for container-to-container traffic on the same network.- Healthcheck
CMDvsCMD-SHELL.CMDruns the array directly with no shell, sopg_isready && echo okfails; useCMD-SHELLfor pipelines and expansions. - Missing
start_period. A database that takes 20 s to initialise is marked unhealthy after three 5 s retries and the dependent service never starts, which looks like a connection error. docker compose upreusing an old container. Edited environment variables only apply after--force-recreate; a staleDATABASE_URLsurvives a config change.- Docker's embedded DNS caching after a restart. A container that resolved
dbbefore it was recreated can hold the old IP for the process lifetime. Restart the client container, or resolve per connection.
Related tools. Build the exact healthcheck URL and connection probes with the cURL builder, split and inspect the parts of a DATABASE_URL or REDIS_URL with the URL parser, and validate the compose YAML before up with the YAML validator — an indentation error inside depends_on often reads as a networking failure.
Try matching browser tools
All toolsSmall utilities that fit Docker work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Docker guides
All Docker guidesDocker BuildKit failed to solve: Exit Codes, Build Context, and Network
BuildKit puts every failure under one prefix. The exit code after did not complete successfully is the whole diagnosis: 100 is apt, 127 is a missing binary, and cache key is a file outside the context.
Docker Inspect: Go Templates, Format Flags, and JSON Filtering
The fields worth knowing, the array-versus-object trap, and why <no value> silently passes your monitoring check instead of failing it.
Docker Restart Policies: no, on-failure, always, and unless-stopped
What each policy really restarts, why on-failure ignores a clean exit, how backoff hides crash loops, and why health checks never trigger a restart.
Docker Compose Profiles: Multi-Environment Configs and Overrides
Profiles select which services exist; override files change how they run. How the two fit together, and why ports concatenate instead of replacing.
More in Docker
All Docker guidesThe guides filed next to this one in Docker, in library order.