Launch Offer: Use codelaunch30for 30% off

connection refused

This error occurs when the client cannot establish a TCP connection to the PostgreSQL server.

The Connection refused error means the TCP connection to PostgreSQL failed.

Understanding the Error

psql: error: could not connect to server: Connection refused
  Is the server running on host "localhost" (127.0.0.1) and accepting
  TCP/IP connections on port 5432?

No service is listening on the specified host and port.

Common Causes

1. PostgreSQL Not Running

The database server process isn't started.

2. Wrong Port

BASH
# Default port is 5432, but might be different
psql -h localhost -p 5433 mydb  # Wrong port

3. Wrong Host

BASH
psql -h wrong-hostname mydb

4. Firewall Blocking

Network firewall preventing connections on port 5432.

5. PostgreSQL Not Listening on Network

Configured for local socket connections only.

How to Fix It

Solution 1: Start PostgreSQL

BASH
# Linux with systemd
sudo systemctl start postgresql
sudo systemctl status postgresql

# macOS with Homebrew
brew services start postgresql@15

# Check if running
ps aux | grep postgres

Solution 2: Check Port

BASH
# Check what port PostgreSQL is using
sudo netstat -tlnp | grep postgres
# or
ss -tlnp | grep postgres
# or
lsof -i :5432

# Connect with correct port
psql -h localhost -p 5432 mydb

Solution 3: Check postgresql.conf

BASH
# Find config file
psql -U postgres -c "SHOW config_file;"

# Edit configuration
sudo nano /etc/postgresql/15/main/postgresql.conf
# Listen on all interfaces
listen_addresses = '*'
port = 5432

Solution 4: Configure pg_hba.conf

BASH
# Find hba file
psql -U postgres -c "SHOW hba_file;"

# Add entries for remote connections
sudo nano /etc/postgresql/15/main/pg_hba.conf
# TYPE  DATABASE    USER    ADDRESS         METHOD
host    all         all     0.0.0.0/0       md5
host    all         all     ::/0            md5

Solution 5: Configure Firewall

BASH
# Ubuntu/Debian with ufw
sudo ufw allow 5432/tcp
sudo ufw reload

# CentOS/RHEL with firewalld
sudo firewall-cmd --permanent --add-port=5432/tcp
sudo firewall-cmd --reload

# Check if port is open
sudo ufw status

Solution 6: Use Local Socket Instead

BASH
# Connect via Unix socket (Linux)
psql -U postgres mydb
# or
psql -h /var/run/postgresql mydb

# On macOS with Homebrew
psql -h /tmp mydb

Troubleshooting Checklist

BASH
# 1. Is PostgreSQL running?
sudo systemctl status postgresql

# 2. What port is it listening on?
sudo netstat -tlnp | grep postgres

# 3. Can you connect locally?
psql -U postgres

# 4. Is the port reachable?
telnet localhost 5432
# or
nc -zv localhost 5432

# 5. Check PostgreSQL logs
sudo tail -f /var/log/postgresql/postgresql-15-main.log

Best Practices

  1. Monitor PostgreSQL with health checks
  2. Use connection pooling for reliability
  3. Configure automatic restart on failure
  4. Document connection requirements
  5. Test connectivity from application servers