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
# 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 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