Error: connect ECONNREFUSED 127.0.0.1:5432
Node canβt connect to the server at that address. The service isnβt running or the address is wrong.
Why this happens
ECONNREFUSED means the TCP connection was actively rejected β nothing is listening on that host/port combination. This typically happens when the target service (database, API, cache) hasnβt started yet, crashed, or is bound to a different interface. In Docker environments, localhost refers to the container itself, not the host machine.
Fix 1: Check if the service is running
# For a database
sudo systemctl status [postgresql](/blog/what-is-postgresql/)
# For any port
lsof -i :5432
Fix 2: Check the connection string
// β Wrong port or host
const client = new Client({ host: 'localhost', port: 5433 });
// β
Correct
const client = new Client({ host: 'localhost', port: 5432 });
Fix 3: Docker β use the service name, not localhost
// β Inside Docker, localhost is the container itself
const client = new Client({ host: 'localhost' });
// β
Use the [Docker Compose](/blog/docker-compose-validator/) service name
const client = new Client({ host: 'db' });
Alternative solution: Add retry logic
Services may not be ready immediately. Add a connection retry with backoff:
async function connectWithRetry(client, retries = 5) {
for (let i = 0; i < retries; i++) {
try { await client.connect(); return; }
catch { await new Promise(r => setTimeout(r, 1000 * (i + 1))); }
}
throw new Error('Failed to connect after retries');
}
Prevention
- Use health checks in Docker Compose (
depends_onwithcondition: service_healthy) to ensure services start in order. - Store connection strings in environment variables so theyβre easy to change per environment.
Related: Node.js: EADDRINUSE β Port Already in Use β How to Fix It Β· ERR_CONNECTION_REFUSED β How to Fix It Β· Docker Network Not Found Fix