Skip to main content

Node.js ECONNREFUSED — diagnosing connection refused errors

TL;DR

How to diagnose and resolve ECONNREFUSED errors in Node.js when connecting to databases, caches, or upstream services.

Key facts

Topic
Production error triage
Stack
Node.js / Linux

TL;DR

ECONNREFUSED (connection refused) occurs when your Node.js application attempts to connect to a TCP endpoint and receives an active rejection. The target service is unreachable — either it is not running, is bound to a different interface, or a firewall is blocking the port.

Common causes

  • The target service (database, Redis, external API) is down or still starting
  • The service is listening on 127.0.0.1 but your app connects to 0.0.0.0 or the server's public IP
  • A firewall rule (UFW, iptables, security group) blocks the port
  • DNS resolution returns a stale or incorrect IP address

Diagnosis workflow

Verify the target service is running and listening:

sudo ss -tlnp | grep :5432
systemctl status postgresql

Test connectivity directly:

nc -zv 127.0.0.1 5432
curl -v telnet://db-host:5432

Check firewall rules:

sudo ufw status
sudo iptables -L -n

Quick fixes

If the service is down, start it:

sudo systemctl start postgresql
sudo systemctl enable postgresql

If it is binding to localhost only, update its config to listen on the correct interface. For PostgreSQL, edit postgresql.conf and set listen_addresses = '0.0.0.0'. For Redis, update the bind directive in redis.conf.

Resilient application code

Implement connection retries with backoff in your Node.js application rather than failing on the first attempt:

const MAX_RETRIES = 5;
const BACKOFF_MS = 1000;

async function connectWithRetry(attempt = 1) {
  try {
    return await pool.connect();
  } catch (err) {
    if (attempt >= MAX_RETRIES) throw err;
    await new Promise(r => setTimeout(r, BACKOFF_MS * attempt));
    return connectWithRetry(attempt + 1);
  }
}

Where Reflex helps

Reflex monitors TCP connectivity between your application and its dependencies. When a connection-refused signal appears, Reflex can verify the dependent service state, restart it if necessary, and confirm your application recovers — all with a full audit trail. See How it works.