Scenario
A newly deployed application server cannot connect to the PostgreSQL database. psql -h db_host -U app_user -d mydb returns psql: error: connection to server at "10.0.1.50", port 5432 failed: Connection refused. The DBA verifies PostgreSQL is running with pg_ctl status. Port 5432 is open in the firewall. The issue is that listen_addresses = 'localhost' — PostgreSQL is only accepting Unix socket and loopback connections.
How to Identify
Conditions:
Connection refused from a remote host but not from localhost
listen_addresses set to localhost or 127.0.0.1 only
- PostgreSQL running but not listening on the network interface the client is connecting to
pg_hba.conf may further restrict even if listen_addresses is correct
- Firewall or security group blocking port 5432
Analysis Steps
-- Check what addresses PostgreSQL is listening on
SHOW listen_addresses;
-- 'localhost' = only Unix socket + 127.0.0.1 (no remote TCP connections)
-- '*' = all network interfaces (allows remote connections)
-- '10.0.1.50' = specific IP only
-- Check what's in pg_hba.conf for the connecting user/database
SELECT type, database, user_name, address, auth_method
FROM pg_hba_file_rules
ORDER BY line_num;
-- 'host' type requires TCP connection; 'local' is Unix socket only
-- If no matching rule exists for the remote IP → connection rejected
-- Check if PostgreSQL is actually listening on port 5432 (OS level):
-- ss -tlnp | grep 5432
-- netstat -tlnp | grep 5432
-- Expected: 0.0.0.0:5432 (all IPs) or specific IP:5432
-- Check firewall rules (OS level):
-- iptables -L -n | grep 5432
-- ufw status | grep 5432
-- Test network connectivity from app server (OS level):
-- telnet db_host 5432
-- nc -zv db_host 5432
-- pg_isready -h db_host -p 5432
Pitfalls
listen_addresses change requires a full PostgreSQL restart — a configuration reload is not sufficient.
- After fixing
listen_addresses, the pg_hba.conf must also allow the client IP — both must be correct for connection to succeed.
- Setting
listen_addresses = '*' allows connections from all interfaces. In cloud environments, security groups/firewall rules should be the primary network filter — but avoid exposing PostgreSQL port to the internet.
pg_hba.conf host rules match TCP connections; local rules match Unix socket connections. Ensure the correct type is used.
- Connection might be refused by the OS firewall even if PostgreSQL is configured correctly — check both layers.
Resolution Approach
Check in this order: (1) listen_addresses must include the IP PostgreSQL should accept on, (2) pg_hba.conf must have a matching rule for the client IP, (3) OS firewall must allow port 5432 from the client.