Fix "PostgreSQL connection refused port 5432" Error

Getting the "PostgreSQL connection refused port 5432" error in your Node.js, Python, Java, or Ruby application? This complete guide shows you how to start PostgreSQL service, configure connection settings, and fix authentication issues on all platforms.

PostgreSQL Node.js Python Java Ruby on Rails Django

What This Error Looks Like

psql Command Line Error:
psql: error: connection to server at "localhost" (127.0.0.1), port 5432 failed:
Connection refused
    Is the server running on that host and accepting TCP/IP connections?

psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed:
No such file or directory
    Is the server running locally and accepting connections on that socket?
Node.js / pg Error:
Error: connect ECONNREFUSED 127.0.0.1:5432
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1144:16)
    at Protocol._enqueue (node_modules/pg/lib/connection.js:109:16)

Error: getaddrinfo ECONNREFUSED localhost:5432
Python / psycopg2 Error:
psycopg2.OperationalError: connection to server at "localhost" (127.0.0.1), port 5432 failed:
Connection refused
    Is the server running on that host and accepting TCP/IP connections?

django.db.utils.OperationalError: connection to server at "localhost" (::1), port 5432 failed:
Connection refused
Java / JDBC Error:
org.postgresql.util.PSQLException: Connection to localhost:5432 refused.
Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.

java.net.ConnectException: Connection refused (Connection refused)
    at java.base/java.net.PlainSocketImpl.socketConnect(Native Method)

Quick Fix (Choose Your Operating System)

The Problem: PostgreSQL service is not running or not accepting TCP/IP connections on port 5432

  1. Open Services app: Press Win + R, type services.msc
  2. Find "postgresql-x64-XX" service (XX is version number)
  3. Right-click → Start
  4. Test: psql -h localhost -U postgres
  1. Open Terminal
  2. Start PostgreSQL: brew services start postgresql
  3. Verify: psql -h localhost -U postgres
  4. Or check: brew services list
  1. Open Terminal
  2. Start PostgreSQL: sudo systemctl start postgresql
  3. Verify: psql -h localhost -U postgres
  4. Check status: sudo systemctl status postgresql

Complete Troubleshooting Guide

1 Understand the Error

Connection refused on port 5432 means:

  • PostgreSQL server is not running (most common - 80% of cases)
  • PostgreSQL is only listening on Unix socket, not TCP/IP
  • PostgreSQL is running on a different port
  • PostgreSQL's listen_addresses is too restrictive
  • Firewall blocking port 5432
  • pg_hba.conf rejecting connection
Unix Socket vs TCP/IP: On Linux/macOS, psql often connects via Unix socket (/var/run/postgresql/.s.PGSQL.5432) by default, while applications use TCP/IP (localhost:5432). If psql works but your app doesn't, this is likely the issue.

2 Check if PostgreSQL is Running

Check PostgreSQL Service Status

cmd
# Method 1: Services GUI
# Press Win + R, type: services.msc
# Look for "postgresql-x64-XX" (XX is version like 15, 16)
# Check if Status shows "Running"

# Method 2: Command line
sc query postgresql-x64-15

# Method 3: PowerShell
Get-Service postgresql*

# Method 4: Check if port 5432 is listening
netstat -an | findstr :5432

Expected Output if Running:

SERVICE_NAME: postgresql-x64-15
STATE       : 4  RUNNING
TCP    0.0.0.0:5432    0.0.0.0:0    LISTENING

Check PostgreSQL Service Status

bash
# Method 1: Homebrew services
brew services list | grep postgresql

# Method 2: Check process
ps aux | grep postgres

# Method 3: Check if port 5432 is listening
lsof -i :5432
# or
netstat -an | grep 5432

# Method 4: Try connecting
psql -h localhost -U postgres

Expected Output if Running:

postgresql@14 started username ~/Library/LaunchAgents/[email protected]

# Or with lsof:
postgres 12345 user   5u  IPv6 0x... TCP localhost:5432 (LISTEN)
postgres 12345 user   6u  IPv4 0x... TCP localhost:5432 (LISTEN)

Check PostgreSQL Service Status

bash
# Method 1: Using systemctl
sudo systemctl status postgresql

# Method 2: Check process
ps aux | grep postgres

# Method 3: Check if port 5432 is listening
sudo lsof -i :5432
# or
sudo netstat -tulpn | grep :5432
# or
sudo ss -tulpn | grep :5432

# Method 4: Try connecting
psql -h localhost -U postgres

Expected Output if Running:

● postgresql.service - PostgreSQL RDBMS
   Loaded: loaded (/lib/systemd/system/postgresql.service; enabled)
   Active: active (exited) since Mon 2024-01-15 10:30:00 UTC

postgres 12345  0.0  1.2  /usr/lib/postgresql/15/bin/postgres

3 Start PostgreSQL Service

Start PostgreSQL on Windows

Method 1: Services GUI (Easiest)

  1. Press Win + R, type services.msc, press Enter
  2. Find "postgresql-x64-15" (or your version number)
  3. Right-click → "Start"
  4. Optional: Right-click → "Properties" → Set "Startup type" to "Automatic"

Method 2: Command Line (Run as Administrator)

cmd
# Replace 15 with your PostgreSQL version
net start postgresql-x64-15

# Enable auto-start on boot
sc config postgresql-x64-15 start=auto

Method 3: PowerShell (Run as Administrator)

powershell
# Start PostgreSQL
Start-Service postgresql-x64-15

# Set to start automatically
Set-Service postgresql-x64-15 -StartupType Automatic

Start PostgreSQL on macOS

Method 1: Using Homebrew Services (Recommended)

bash
# Start PostgreSQL and run at login
brew services start postgresql@15

# Or for latest version:
brew services start postgresql

# Check status
brew services list

Method 2: Manual Start

bash
# Start PostgreSQL manually
pg_ctl -D /opt/homebrew/var/postgresql@15 start

# Or find data directory:
brew info postgresql@15
# Look for "Data directory" path
Note: Use brew services start (not run) to make PostgreSQL start automatically on login.

Start PostgreSQL on Linux

Using systemctl (Ubuntu/Debian/CentOS/RHEL)

bash
# Start PostgreSQL
sudo systemctl start postgresql

# Enable auto-start on boot
sudo systemctl enable postgresql

# Check status
sudo systemctl status postgresql

# Restart PostgreSQL
sudo systemctl restart postgresql

Manual Start (if systemctl not available)

bash
# Find PostgreSQL version and data directory
pg_lsclusters  # Debian/Ubuntu

# Start specific cluster
sudo pg_ctlcluster 15 main start

# Or manual start:
sudo -u postgres pg_ctl -D /var/lib/postgresql/15/main start

4 Configure PostgreSQL to Accept TCP/IP Connections

If PostgreSQL is running but still connection refused, it may only be listening on Unix socket.

Edit postgresql.conf

bash
# Find postgresql.conf location:
# Linux: /etc/postgresql/15/main/postgresql.conf
# macOS: /opt/homebrew/var/postgresql@15/postgresql.conf
# Windows: C:\Program Files\PostgreSQL\15\data\postgresql.conf

# Edit the file (use sudo on Linux):
sudo nano /etc/postgresql/15/main/postgresql.conf

Required settings in postgresql.conf:

conf
# Find and uncomment/change these lines:

# Allow connections from localhost
listen_addresses = 'localhost'
# Or allow all: listen_addresses = '*'

# Ensure port is 5432
port = 5432

# Save file and restart PostgreSQL

Restart PostgreSQL After Configuration Changes

bash
# Linux:
sudo systemctl restart postgresql

# macOS:
brew services restart postgresql@15

# Windows (Command Prompt as Admin):
net stop postgresql-x64-15 && net start postgresql-x64-15

5 Configure pg_hba.conf (Authentication)

pg_hba.conf controls which clients can connect to PostgreSQL.

bash
# Find pg_hba.conf location:
# Linux: /etc/postgresql/15/main/pg_hba.conf
# macOS: /opt/homebrew/var/postgresql@15/pg_hba.conf
# Windows: C:\Program Files\PostgreSQL\15\data\pg_hba.conf

# Edit the file:
sudo nano /etc/postgresql/15/main/pg_hba.conf

Add/modify these lines in pg_hba.conf:

conf
# TYPE  DATABASE        USER            ADDRESS                 METHOD

# For development - trust localhost connections (no password):
host    all             all             127.0.0.1/32            trust
host    all             all             ::1/128                 trust

# For production - require password:
host    all             all             127.0.0.1/32            md5
host    all             all             ::1/128                 md5

# Local Unix socket connections (works for psql):
local   all             all                                     trust
Security Note: Using trust allows connections without password. Only use in development. In production, use md5 or scram-sha-256.

After editing pg_hba.conf, reload PostgreSQL:

bash
# Linux:
sudo systemctl reload postgresql

# macOS:
brew services restart postgresql@15

# Or:
psql -U postgres -c "SELECT pg_reload_conf();"

6 Test PostgreSQL Connection

Test with psql

bash
# Test TCP/IP connection (what your app uses)
psql -h localhost -p 5432 -U postgres

# If successful, you'll see:
# psql (15.3)
# Type "help" for help.
# postgres=#

# Test specific database:
psql -h localhost -p 5432 -U postgres -d mydatabase

Test from Application Code

Node.js / pg:

javascript
const { Client } = require('pg');

const client = new Client({
  host: 'localhost',
  port: 5432,
  user: 'postgres',
  password: 'yourpassword',
  database: 'postgres'
});

client.connect()
  .then(() => console.log('✓ PostgreSQL connected successfully'))
  .catch(err => console.error('✗ PostgreSQL connection error:', err.message))
  .finally(() => client.end());

Python / psycopg2:

python
import psycopg2

try:
    conn = psycopg2.connect(
        host="localhost",
        port=5432,
        user="postgres",
        password="yourpassword",
        database="postgres"
    )
    print("✓ PostgreSQL connected successfully")
    conn.close()
except Exception as e:
    print(f"✗ PostgreSQL connection error: {e}")

Common Issues and Solutions

Issue 1: psql Works But Application Doesn't

Symptoms: psql connects fine, but your app gets connection refused

Cause: psql uses Unix socket, your app uses TCP/IP

Solutions:

  1. Test with: psql -h localhost -U postgres (forces TCP/IP)
  2. If that fails, PostgreSQL isn't listening on TCP/IP
  3. Check postgresql.conf: listen_addresses = 'localhost'
  4. Check pg_hba.conf has host rules (not just local)
  5. Restart PostgreSQL after config changes

Issue 2: "FATAL: password authentication failed"

This is different from connection refused - it means PostgreSQL is running and accepting connections, but authentication failed.

Solutions:

bash
# Reset postgres user password:
# Linux/macOS:
sudo -u postgres psql
ALTER USER postgres PASSWORD 'newpassword';
\q

# Or change pg_hba.conf to 'trust' for development:
# host    all    all    127.0.0.1/32    trust

Issue 3: PostgreSQL Running on Different Port

Check which port PostgreSQL is actually using:

bash
# Check postgresql.conf for port setting
grep port /etc/postgresql/15/main/postgresql.conf

# Check which ports PostgreSQL is listening on
sudo lsof -i -P | grep postgres
# or
sudo netstat -tulpn | grep postgres

If PostgreSQL is on a different port, update your connection string to match.

Issue 4: Multiple PostgreSQL Installations

Problem: You have multiple PostgreSQL versions and wrong one is running

bash
# Check all PostgreSQL installations:
# macOS:
brew list | grep postgresql

# Linux:
dpkg -l | grep postgresql  # Debian/Ubuntu
rpm -qa | grep postgresql  # CentOS/RHEL

# List all running postgres processes:
ps aux | grep postgres

Solution: Stop wrong version, start correct version, or configure your app to use the running version's port.

Quick Reference Commands

cheatsheet
POSTGRESQL SERVICE COMMANDS BY OS
==================================

Windows:
  Check:   sc query postgresql-x64-15
  Start:   net start postgresql-x64-15
  Stop:    net stop postgresql-x64-15
  Restart: net stop postgresql-x64-15 && net start postgresql-x64-15

macOS (Homebrew):
  Check:   brew services list | grep postgresql
  Start:   brew services start postgresql@15
  Stop:    brew services stop postgresql@15
  Restart: brew services restart postgresql@15

Linux (systemd):
  Check:   sudo systemctl status postgresql
  Start:   sudo systemctl start postgresql
  Stop:    sudo systemctl stop postgresql
  Enable:  sudo systemctl enable postgresql
  Restart: sudo systemctl restart postgresql
  Reload:  sudo systemctl reload postgresql

CONFIGURATION FILES
===================
Linux:   /etc/postgresql/15/main/postgresql.conf
         /etc/postgresql/15/main/pg_hba.conf
macOS:   /opt/homebrew/var/postgresql@15/postgresql.conf
         /opt/homebrew/var/postgresql@15/pg_hba.conf
Windows: C:\Program Files\PostgreSQL\15\data\postgresql.cfg
         C:\Program Files\PostgreSQL\15\data\pg_hba.conf

TEST CONNECTION
===============
CLI:     psql -h localhost -p 5432 -U postgres
Port:    lsof -i :5432 (Mac/Linux) | netstat -an | findstr :5432 (Win)
URL:     postgresql://postgres:password@localhost:5432/database

Still Having Issues?

Debugging checklist:

Visit our Interactive Diagnostic Wizard for personalized help.