How to fix Error: connect ECONNREFUSED 127.0.0.1:5432 in Node.js

Node.jsINTERMEDIATEHIGHUpdated Dec 9, 2025ยท 272 views

This error occurs when Node.js attempts to establish a TCP connection to a server (database, API, or service) but the connection is actively refused. The target server is either not running, not listening on the specified port, or actively rejecting connections due to firewall rules or network configuration.

Quick fix

Fixes ECONNREFUSED

# Linux/macOS
sudo systemctl status postgresql
# or
ps aux | grep postgres

# Check if PostgreSQL is listening on port 5432
sudo lsof -i :5432
# or
netstat -an | grep 5432
  1. Verify the target service is running
  2. Verify connection configuration
  3. Use 127.0.0.1 instead of localhost
  4. Implement connection retry logic
node.js โ€” error
# Linux/macOS
sudo systemctl status postgresql
# or
ps aux | grep postgres
# Check if PostgreSQL is listening on port 5432
sudo lsof -i :5432
# or
netstat -an | grep 5432
Error: connect ECONNREFUSED 127.0.0.1:5432

What this error means

ECONNREFUSED is a Node.js error code indicating that a connection attempt was actively refused by the target machine. This happens when your application tries to connect to a server on a specific host and port, but nothing is listening on that address or the connection is blocked. The error is part of Node.js's network error codes and represents a TCP-level connection failure. Unlike timeout errors (ETIMEDOUT), ECONNREFUSED means the target machine responded and explicitly rejected the connection. This is typically because no process is bound to the port you're trying to reach. This error commonly occurs with database connections (PostgreSQL on port 5432, MongoDB on port 27017, Redis on port 6379), HTTP API calls, or inter-service communication in microservice architectures. The 127.0.0.1 address indicates localhost, meaning your application is trying to connect to a service on the same machine.

Typical symptoms

  • Application crashes on startup when attempting database connection
  • Error message shows "connect ECONNREFUSED" with IP address and port number
  • Database queries fail with connection refused errors
  • HTTP requests to localhost services fail immediately without timeout
  • Docker containers cannot connect to host services
  • CI/CD pipeline fails during integration tests requiring database
  • Development server cannot connect to local database or API

Common causes

  1. Database server or target service is not running before Node.js application starts
  2. Application configured with incorrect port number for the target service
  3. Service is listening on a different network interface (0.0.0.0 vs 127.0.0.1)
  4. Port is already occupied by another application preventing service from starting
  5. Firewall rules blocking connections to the specified port
  6. Docker networking issues when containers try to reach host services
  7. Node.js 17+ using IPv6 (::1) instead of IPv4 (127.0.0.1) for localhost resolution
  8. Service crashed or failed to start due to configuration errors

How to fix "Error: connect ECONNREFUSED 127.0.0.1:5432"

1Verify the target service is running

Check if the service you're trying to connect to is actually running:

For PostgreSQL:

bash
# Linux/macOS
sudo systemctl status postgresql
# or
ps aux | grep postgres

# Check if PostgreSQL is listening on port 5432
sudo lsof -i :5432
# or
netstat -an | grep 5432

For MongoDB:

bash
sudo systemctl status mongod
sudo lsof -i :27017

For custom Node.js services:

bash
# Check if anything is listening on the port
lsof -i :3000
netstat -an | grep LISTEN | grep 3000

If nothing is listening on the port, start the required service before running your application.

2Verify connection configuration

Double-check that your application is using the correct host and port:

javascript
// PostgreSQL connection example
const { Client } = require('pg');

const client = new Client({
  host: '127.0.0.1',      // Verify this matches where service is running
  port: 5432,              // Verify correct port
  database: 'mydb',
  user: 'postgres',
  password: 'password'
});

client.connect()
  .then(() => console.log('Connected successfully'))
  .catch(err => {
    console.error('Connection error:', err.code, err.message);
    console.error('Attempted connection to:', client.host + ':' + client.port);
  });

Common mistakes:
- Using port 5432 when PostgreSQL is on 5433
- Forgetting to specify protocol (http:// vs https://)
- Mixing up localhost, 127.0.0.1, and 0.0.0.0

3Use 127.0.0.1 instead of localhost

Node.js 17+ prefers IPv6, which can cause connection issues. Explicitly use IPv4:

javascript
// Before (may fail on Node.js 17+)
const client = new Client({
  host: 'localhost',
  port: 5432
});

// After (works reliably)
const client = new Client({
  host: '127.0.0.1',
  port: 5432
});

Or configure your service to listen on both IPv4 and IPv6:

For PostgreSQL in postgresql.conf:

bash
listen_addresses = '*'

For custom Node.js servers:

javascript
// Listen on all interfaces
app.listen(3000, '0.0.0.0', () => {
  console.log('Server listening on all interfaces port 3000');
});
4Implement connection retry logic

Add retry logic to handle services that take time to start up:

javascript
async function connectWithRetry(maxRetries = 5, delay = 2000) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      await client.connect();
      console.log('Connected successfully');
      return;
    } catch (err) {
      if (err.code === 'ECONNREFUSED') {
        console.log(`Connection attempt ${attempt}/${maxRetries} failed`);
        if (attempt === maxRetries) {
          throw new Error('Max retries reached. Service may not be running.');
        }
        console.log(`Retrying in ${delay}ms...`);
        await new Promise(resolve => setTimeout(resolve, delay));
      } else {
        // Different error, don't retry
        throw err;
      }
    }
  }
}

connectWithRetry()
  .catch(err => {
    console.error('Failed to connect:', err.message);
    process.exit(1);
  });

This is especially useful in Docker environments where services start in parallel.

5Check firewall and security settings

Ensure firewall rules aren't blocking the connection:

Linux (UFW):

bash
# Check firewall status
sudo ufw status

# Allow PostgreSQL port
sudo ufw allow 5432/tcp

# For local development, you can temporarily disable
sudo ufw disable

macOS:

bash
# Check if firewall is blocking the port
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate

Windows:

powershell
# Check if port is blocked
Test-NetConnection -ComputerName 127.0.0.1 -Port 5432

For Docker containers trying to reach host services:

yaml
# docker-compose.yml
services:
  app:
    network_mode: "host"  # Access host services directly
    # Or use host.docker.internal on Docker Desktop
6Fix Docker networking issues

When running Node.js in Docker and connecting to host services:

Option 1 - Use host.docker.internal (Docker Desktop):

javascript
const client = new Client({
  host: 'host.docker.internal',  // Docker Desktop
  port: 5432
});

Option 2 - Use host network mode:

yaml
# docker-compose.yml
services:
  app:
    network_mode: "host"

Option 3 - Run database in Docker too:

yaml
services:
  app:
    depends_on:
      - postgres
    environment:
      DATABASE_HOST: postgres  # Use service name

  postgres:
    image: postgres:15
    ports:
      - "5432:5432"

Option 4 - On Linux, use host gateway:

bash
docker run --add-host=host.docker.internal:host-gateway your-image

Advanced notes

Debugging Connection Issues Systematically

Use telnet or nc (netcat) to test if the port is reachable:

bash
# Test if port is accessible
telnet 127.0.0.1 5432
# or
nc -zv 127.0.0.1 5432

If this fails, the issue is at the service level, not your Node.js code.

PostgreSQL Specific Considerations

PostgreSQL's pg_hba.conf controls connection permissions. Ensure localhost connections are allowed:

bash
# pg_hba.conf
host    all             all             127.0.0.1/32            md5
host    all             all             ::1/128                 md5

After changing, reload PostgreSQL:

bash
sudo systemctl reload postgresql

MongoDB IPv6 Issues

MongoDB may bind only to IPv6 on some systems. Check mongod.conf:

yaml
net:
  bindIp: 127.0.0.1,::1  # Both IPv4 and IPv6
  port: 27017

Environment-Specific Connection Strings

Use environment variables to handle different environments:

javascript
const client = new Client({
  host: process.env.DB_HOST || '127.0.0.1',
  port: parseInt(process.env.DB_PORT || '5432'),
  database: process.env.DB_NAME || 'mydb'
});

.env for development:

bash
DB_HOST=127.0.0.1
DB_PORT=5432

.env.docker for Docker:

bash
DB_HOST=postgres
DB_PORT=5432

Health Checks in Production

Implement health check endpoints that verify database connectivity:

javascript
app.get('/health', async (req, res) => {
  try {
    await client.query('SELECT 1');
    res.status(200).json({ status: 'healthy', database: 'connected' });
  } catch (err) {
    if (err.code === 'ECONNREFUSED') {
      res.status(503).json({
        status: 'unhealthy',
        database: 'connection_refused',
        error: 'Database service not reachable'
      });
    } else {
      res.status(503).json({ status: 'unhealthy', error: err.message });
    }
  }
});

CI/CD Pipeline Considerations

In GitHub Actions or similar CI environments, ensure services are ready before tests:

yaml
services:
  postgres:
    image: postgres:15
    options: >-
      --health-cmd pg_isready
      --health-interval 10s
      --health-timeout 5s
      --health-retries 5
    ports:
      - 5432:5432

Port Conflicts

If you get ECONNREFUSED because the port is taken, find what's using it:

bash
# Linux/macOS
sudo lsof -i :5432
# Kill the process if needed
sudo kill -9 <PID>

# Windows
netstat -ano | findstr :5432
taskkill /PID <PID> /F

Frequently asked questions

What does "ECONNREFUSED" mean?
js error code indicating that a connection attempt was actively refused by the target machine. This happens when your application tries to connect to a server on a specific host and port, but nothing is listening on that address or the connection is blocked. js's network error codes and represents a TCP-level connection failure.
How do I fix "ECONNREFUSED"?
This error occurs when Node.js attempts to establish a TCP connection to a server (database, API, or service) but the connection is actively refused. The target server is either not running, not listening on the specified port, or actively rejecting connections due to firewall rules or network configuration.
What causes "ECONNREFUSED"?
Database server or target service is not running before Node.js application starts Application configured with incorrect port number for the target service Service is listening on a different network interface (0.0.0.0 vs 127.0.0.1)
Is the "ECONNREFUSED" error serious?
Yes. This is a high-severity error that usually blocks work until it is fixed, but the steps above resolve it.

Official resources & further reading