Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readDocker
#Docker#Docker Compose#Networking#Debugging
3D illustration of two containers with a loopback arrow to itself and a cyan route to the other container

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:

yaml
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:

yaml
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: 10s

depends_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:

bash
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 app

getent 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 → ToAddress to useWhy
container → containerservice-name:internal-portCompose DNS on the shared network
host → containerlocalhost:published-portPort mapping on the host's interface
container → hosthost.docker.internal:portDocker Desktop; needs host-gateway on Linux
container → itself127.0.0.1:portOnly if the server binds 0.0.0.0 or loopback
container → internetnormal DNSBridge network with NAT
Startup controlWaits forUse for
depends_on: [db]Container createdNothing about readiness
condition: service_startedProcess startedSame weakness as above
condition: service_healthyHealthcheck passingDatabases, brokers, migrations
restart: on-failure + retry in appFirst successful connectionRobust option in production
docker compose up --waitAll healthchecks greenCI 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:

js
// 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:

js
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:

yaml
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.

yaml
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:

js
const pool = new Pool({ connectionString: url, max: 10, connectionTimeoutMillis: 5000 }); pool.on('error', (err) => log.warn({ err }, 'idle client error')); // never throw here

Common 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.
  • expose vs ports. expose documents an internal port and publishes nothing; ports maps to the host. Neither is required for container-to-container traffic on the same network.
  • Healthcheck CMD vs CMD-SHELL. CMD runs the array directly with no shell, so pg_isready && echo ok fails; use CMD-SHELL for 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 up reusing an old container. Edited environment variables only apply after --force-recreate; a stale DATABASE_URL survives a config change.
  • Docker's embedded DNS caching after a restart. A container that resolved db before 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 tools

Small utilities that fit Docker work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Docker guides

More in Docker

All Docker guides

The guides filed next to this one in Docker, in library order.