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
Here's what each line means:
- at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16): The TCP connection attempt completed with a refusal, meaning no service was listening on the target port.
- at Object.query (src/db/connection.js:14:22): Your database connection module at line 14 attempted a query that triggered the pool to open a new connection.
- at UserRepository.findAll (src/repositories/userRepository.js:8:30): The repository layer initiated the database call that ultimately failed due to the refused connection.
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.
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;
}
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:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- 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:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- 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)
- Verify the target database service is running and accessible.
- Update environment variables with the correct host and port.
- Run the test suite locally to confirm the fix passes.
- Open a pull request with the changes.
- Wait for CI to pass and get a teammate review.
- 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.