πŸ”§ Error Fixes
Β· 1 min read

Node.js: ECONNREFUSED β€” Connection Refused β€” How to Fix It


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_on with condition: 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

πŸ“˜