Skip to main content

rawops.dev

P1

Connection Refused — PostgreSQL Troubleshooting Guide

Troubleshoot PostgreSQL connection failures. Covers service status, listen address configuration, pg_hba.conf authentication rules, connection limits, and restart procedures.

10 min7 steps
Progress: 0/7 steps
0%

Verify the PostgreSQL service is active and listening.

systemctl status postgresql && ss -tlnp | grep 5432
Expected: Service should be 'active (running)' and listening on port 5432.

Read recent logs for error messages.

tail -30 /var/log/postgresql/postgresql-*-main.log 2>/dev/null || journalctl -u postgresql --since '30 minutes ago' --no-pager | tail -30
Expected: Look for 'FATAL' errors: authentication failures, connection limit reached, or startup issues.

Verify PostgreSQL is configured to accept connections from the right addresses.

grep -E '^listen_addresses|^port' /etc/postgresql/*/main/postgresql.conf
Expected: listen_addresses should include '*' or the specific IP. Default 'localhost' only allows local connections.

Verify client authentication is configured correctly.

cat /etc/postgresql/*/main/pg_hba.conf | grep -v '^#' | grep -v '^$'
Expected: Each line defines who can connect, from where, and how. Look for your client IP/subnet and auth method.

Verify the server hasn't hit its max connections limit.

sudo -u postgres psql -c 'SELECT count(*) as active, (SELECT setting FROM pg_settings WHERE name = \'max_connections\') as max FROM pg_stat_activity;'
Expected: If active is close to max, connections are exhausted. Increase max_connections or close idle connections.

Try connecting locally to isolate network vs auth issues.

sudo -u postgres psql -c 'SELECT version();'
Expected: Should show PostgreSQL version. If this fails, PostgreSQL itself has an issue.

After fixing configuration, restart to apply changes.

systemctl restart postgresql && systemctl status postgresql
Expected: Service should start without errors.
Restarting PostgreSQL disconnects all active clients. Consider 'pg_ctl reload' for config-only changes.