How It Works Features Pricing Blog Error Guides
Log In Start Free Trial
Node.js · JavaScript

Fix Error: connect ECONNREFUSED 127.0.0.1:5432 in Node.js

This error means Node.js cannot reach the server at the specified address and port, usually because the target service (database, API, etc.) is not running or is listening on a different port. Fix it by verifying the service is started and the host/port configuration matches.

Reading the Stack Trace

Error: connect ECONNREFUSED 127.0.0.1:5432 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16) at Protocol._enqueue (node_modules/pg-protocol/dist/protocol.js:28:18) at Client.connect (node_modules/pg/lib/client.js:45:23) at Pool._createConnection (node_modules/pg-pool/index.js:118:26) at Pool.connect (node_modules/pg-pool/index.js:82:10) at Object.query (src/db/connection.js:14:22) at UserRepository.findAll (src/repositories/userRepository.js:8:30) at UserService.getAllUsers (src/services/userService.js:12:38) at Layer.handle [as handle_request] (node_modules/express/lib/router/layer.js:95:5) at next (node_modules/express/lib/router/route.js:144:13)

Here's what each line means:

Common Causes

1. Database service not running

The PostgreSQL server is not started or has crashed, so nothing is listening on port 5432.

const { Pool } = require('pg');
const pool = new Pool({
  host: '127.0.0.1',
  port: 5432,
  database: 'myapp',
});
// PostgreSQL is not running
const result = await pool.query('SELECT * FROM users');

2. Wrong host or port in configuration

The connection string points to the wrong host or port, perhaps a leftover from a different environment.

const pool = new Pool({
  host: process.env.DB_HOST || '127.0.0.1',
  port: process.env.DB_PORT || 5432,
});
// DB_HOST and DB_PORT env vars are not set, defaults don't match actual server

3. Firewall or network policy blocking the port

A firewall rule, Docker network config, or security group is preventing TCP connections to the target port.

// docker-compose.yml exposes 5433 externally but app connects to 5432
const pool = new Pool({ host: 'localhost', port: 5432 });

The Fix

Use environment variables for connection config so each environment can specify the correct host and port. Add a connection timeout so the app fails fast instead of hanging. Catch ECONNREFUSED specifically to log a helpful diagnostic message.

Before (broken)
const { Pool } = require('pg');
const pool = new Pool({
  host: '127.0.0.1',
  port: 5432,
  database: 'myapp',
});

async function query(text, params) {
  const result = await pool.query(text, params);
  return result;
}
After (fixed)
const { Pool } = require('pg');
const pool = new Pool({
  host: process.env.DB_HOST || '127.0.0.1',
  port: parseInt(process.env.DB_PORT, 10) || 5432,
  database: process.env.DB_NAME || 'myapp',
  connectionTimeoutMillis: 5000,
});

async function query(text, params) {
  try {
    const result = await pool.query(text, params);
    return result;
  } catch (err) {
    if (err.code === 'ECONNREFUSED') {
      console.error(`Database connection refused at ${pool.options.host}:${pool.options.port}. Is the server running?`);
    }
    throw err;
  }
}

Testing the Fix

const { query } = require('./connection');

jest.mock('pg', () => {
  const mockQuery = jest.fn();
  const mockPool = { query: mockQuery, options: { host: '127.0.0.1', port: 5432 } };
  return { Pool: jest.fn(() => mockPool), __mockQuery: mockQuery };
});

const { __mockQuery } = require('pg');

describe('Database connection', () => {
  it('returns query results on success', async () => {
    __mockQuery.mockResolvedValue({ rows: [{ id: 1 }] });
    const result = await query('SELECT 1');
    expect(result.rows).toEqual([{ id: 1 }]);
  });

  it('throws and logs on ECONNREFUSED', async () => {
    const err = new Error('connect ECONNREFUSED');
    err.code = 'ECONNREFUSED';
    __mockQuery.mockRejectedValue(err);
    const consoleSpy = jest.spyOn(console, 'error').mockImplementation();
    await expect(query('SELECT 1')).rejects.toThrow('ECONNREFUSED');
    expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Database connection refused'));
    consoleSpy.mockRestore();
  });
});

Run your tests:

npm test

Pushing Through CI/CD

git checkout -b fix/nodejs-econnrefused-handling,git add src/db/connection.js src/db/__tests__/connection.test.js,git commit -m "fix: add ECONNREFUSED error handling and env-based db config",git push origin fix/nodejs-econnrefused-handling

Your CI config should look something like this:

name: CI
on:
  pull_request:
    branches: [main]
jobs:
  test:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:16
        env:
          POSTGRES_PASSWORD: test
        ports:
          - 5432:5432
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'
      - run: npm ci
      - run: npm test -- --coverage
        env:
          DB_HOST: localhost
          DB_PORT: 5432

The Full Manual Process: 18 Steps

Here's every step you just went through to fix this one bug:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. Monitor production to confirm the error is resolved

Total time: 30-60 minutes. For one bug.

Or Let bugstack Fix It in Under 2 minutes

Every step above? bugstack does it automatically.

Step 1: Install the SDK

npm install bugstack-sdk

Step 2: Initialize

const { initBugStack } = require('bugstack-sdk')

initBugStack({ apiKey: process.env.BUGSTACK_API_KEY })

Step 3: There is no step 3.

bugstack handles everything from here:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. Deploys to production (or opens a PR for review)

Time from error to fix deployed: Under 2 minutes.

Human involvement: zero.

Try bugstack Free →

No credit card. 5-minute setup. Cancel anytime.

Deploying the Fix (Manual Path)

  1. Verify the target database service is running and accessible.
  2. Update environment variables with the correct host and port.
  3. Run the test suite locally to confirm the fix passes.
  4. Open a pull request with the changes.
  5. Wait for CI to pass and get a teammate review.
  6. Merge to main and verify the connection works in staging.

Frequently Asked Questions

BugStack runs the fix through your existing test suite, generates additional edge-case tests, and validates that no other modules are affected before marking it safe to deploy.

BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.

Try connecting directly with psql or pg_isready from the same host. If those work, the issue is likely in your app's connection config. If they also fail, the database process needs to be restarted.

Connection pools like pg-pool already handle reconnection. The key is to set a reasonable connectionTimeoutMillis and handle the error gracefully so your app doesn't crash on transient failures.