Launch Offer: Use codelaunch30for 30% off

could not connect to server

This error occurs when PostgreSQL cannot establish a connection to the database server. Common causes include the server not running or network issues.

The could not connect to server error means the 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?

The client cannot reach the PostgreSQL server.

Common Causes

1. PostgreSQL Not Running

The database service isn't started.

2. Wrong Host or Port

BASH
# Trying wrong host
psql -h wronghost -p 5432 mydb

# Trying wrong port
psql -h localhost -p 5433 mydb  # Default is 5432

3. Firewall Blocking Connection

Network firewall preventing access to port 5432.

4. PostgreSQL Not Listening on TCP/IP

Server configured for local connections only.

How to Fix It

Solution 1: Start PostgreSQL

BASH
# Linux (systemd)
sudo systemctl start postgresql
sudo systemctl enable postgresql  # Start on boot

# macOS (Homebrew)
brew services start postgresql

# macOS (Postgres.app)
# Open Postgres.app and click Start

# Check status
sudo systemctl status postgresql

Solution 2: Check Server is Running

BASH
# Check if postgres process exists
ps aux | grep postgres

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

Solution 3: Configure postgresql.conf

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

# Edit postgresql.conf
sudo nano /etc/postgresql/15/main/postgresql.conf

Enable TCP/IP connections:

listen_addresses = 'localhost'  # or '*' for all interfaces
port = 5432

Solution 4: Update pg_hba.conf

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

# Edit to allow connections
sudo nano /etc/postgresql/15/main/pg_hba.conf

Add entries for remote connections:

# TYPE  DATABASE    USER    ADDRESS         METHOD
host    all         all     0.0.0.0/0       md5

Solution 5: Check Firewall

BASH
# Linux (ufw)
sudo ufw allow 5432/tcp

# Linux (firewalld)
sudo firewall-cmd --permanent --add-port=5432/tcp
sudo firewall-cmd --reload

# macOS - check System Preferences > Security > Firewall

Solution 6: Restart PostgreSQL

BASH
# After config changes
sudo systemctl restart postgresql

# Or
sudo pg_ctl restart -D /var/lib/postgresql/data

Docker Considerations

BASH
# Check container is running
docker ps | grep postgres

# Check container logs
docker logs my-postgres-container

# Verify port mapping
docker port my-postgres-container
YAML
# docker-compose.yml
services:
  db:
    image: postgres:15
    ports:
      - "5432:5432"  # Expose port

Best Practices

  1. Use health checks in production to detect connection issues
  2. Configure connection pooling for reliability
  3. Set up monitoring for PostgreSQL availability
  4. Document network requirements for your deployment
  5. Use connection retry logic in applications