0
0
PostgresqlDebug / FixBeginner · 4 min read

How to Fix Connection Refused Error in PostgreSQL

A connection refused error in PostgreSQL usually means the server is not accepting connections on the specified host or port. To fix it, ensure the PostgreSQL server is running, the postgresql.conf allows listening on the right IP, and pg_hba.conf permits your client connection.
🔍

Why This Happens

This error happens when your client tries to connect but the PostgreSQL server is not reachable or refusing connections. Common reasons include the server not running, listening only on localhost, firewall blocking the port, or client IP not allowed.

bash
psql -h 192.168.1.100 -U user dbname
Output
psql: could not connect to server: Connection refused Is the server running on host "192.168.1.100" and accepting TCP/IP connections on port 5432?
🔧

The Fix

First, check if PostgreSQL is running with sudo systemctl status postgresql. Then, edit postgresql.conf to set listen_addresses = '*' to allow connections from any IP. Next, update pg_hba.conf to add your client's IP with proper authentication method. Finally, restart PostgreSQL to apply changes.

bash
# In postgresql.conf
listen_addresses = '*'

# In pg_hba.conf
host    all             all             192.168.1.0/24          md5

# Restart server
sudo systemctl restart postgresql
Output
PostgreSQL server restarted successfully. Now connections from 192.168.1.x are accepted.
🛡️

Prevention

Always verify your PostgreSQL server is running before connecting. Keep listen_addresses and pg_hba.conf updated for your network. Use firewalls to allow port 5432 only for trusted IPs. Regularly test connections after configuration changes to catch issues early.

⚠️

Related Errors

  • Timeout expired: Server is reachable but not responding quickly; check server load and network.
  • Authentication failed: Connection reached server but credentials are wrong; verify username and password.
  • Could not translate host name: DNS or hostname error; check your connection string.

Key Takeaways

Ensure PostgreSQL server is running before connecting.
Set listen_addresses to '*' or specific IPs in postgresql.conf to accept remote connections.
Configure pg_hba.conf to allow client IPs with correct authentication.
Restart PostgreSQL after configuration changes to apply them.
Use firewalls to secure PostgreSQL port and prevent unauthorized access.