Docker: Cannot connect to database from container (ECONNREFUSED / localhost)
Fix database connection errors from Docker containers caused by using localhost instead of bridge network service names or host.docker.internal.
Error Message
connect ECONNREFUSED 127.0.0.1:5432or
psql: error: connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refusedSymptoms
- An application container crashes on startup when attempting to connect to PostgreSQL, MySQL, Redis, or MongoDB.
- You can connect to the database from your host machine via DBeaver /
psql, but the app inside Docker fails to connect.
Why It Happens
Inside a Docker container, localhost (127.0.0.1) points to the container's own isolated network namespace, NOT the host machine and NOT other containers!
┌───────────────────────────┐ ┌───────────────────────────┐
│ Container A (API Server) │ │ Container B (PostgreSQL) │
│ localhost:5432 (Nothing!) │ ──X─►│ localhost:5432 (Listening)│
└───────────────────────────┘ └───────────────────────────┘Solutions
Solution 1: If Both App and Database are in Docker Compose (Recommended)
Use the service name as the hostname. Docker Compose automatically creates a shared DNS bridge:
services:
db:
image: postgres:16-alpine
environment:
POSTGRES_PASSWORD: secret
api:
build: .
environment:
# Use "db" hostname instead of "localhost"
- DATABASE_URL=postgresql://postgres:secret@db:5432/postgres
depends_on:
- dbSolution 2: If the Database is Running Natively on Your Host OS
On macOS & Windows (Docker Desktop):
Use the special DNS name host.docker.internal:
DATABASE_URL=postgresql://postgres:secret@host.docker.internal:5432/postgresOn Linux:
Pass --add-host=host.docker.internal:host-gateway to docker run:
docker run -d --add-host=host.docker.internal:host-gateway \
-e DATABASE_URL="postgresql://postgres:secret@host.docker.internal:5432/postgres" \
my-appRelated Topics
Docker: Container exits immediately with code 0 or 1
Fix containers that terminate immediately upon startup (Exited (0) or Exited (1)) due to foreground process termination, syntax errors, or missing entrypoints.
Docker: no space left on device / Disk space issues
Fix no space left on device errors in Docker by cleaning dangling images, build caches, stopped containers, and unattached volumes.