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
3. Wrong Host
BASH
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
Solution 2: Check Port
BASH
Solution 3: Check postgresql.conf
BASH
# Listen on all interfaces
listen_addresses = '*'
port = 5432
Solution 4: Configure pg_hba.conf
BASH
# TYPE DATABASE USER ADDRESS METHOD
host all all 0.0.0.0/0 md5
host all all ::/0 md5
Solution 5: Configure Firewall
BASH
Solution 6: Use Local Socket Instead
BASH
Troubleshooting Checklist
BASH
Best Practices
- Monitor PostgreSQL with health checks
- Use connection pooling for reliability
- Configure automatic restart on failure
- Document connection requirements
- Test connectivity from application servers