Skip to content
psql: could not connect to server: Connection refused

psql: could not connect to server: Connection refused

DodaTech 2 min read

The error “psql: could not connect to server: Connection refused” means the PostgreSQL client was unable to establish a TCP connection to the server. No PostgreSQL process is accepting connections on the specified host and port.

What It Means

When psql tries to connect, it opens a TCP socket to the target host and port. If the PostgreSQL server is not running, not listening on that interface, or a firewall blocked the connection, the OS returns “Connection refused.”

Why It Happens

  • The PostgreSQL service is stopped or failed to start after a crash.
  • PostgreSQL is configured to listen only on localhost but you connected via the machine’s external IP.
  • A firewall (iptables, UFW, security group) blocks inbound traffic on port 5432.
  • Another process is already using port 5432, preventing PostgreSQL from binding.
  • The postgresql.conf listen_addresses directive is empty or set to a single IP.
  • PostgreSQL is not installed.

How to Fix It

1. Start the PostgreSQL service

sudo systemctl status postgresql
sudo systemctl start postgresql
sudo systemctl enable postgresql

2. Verify PostgreSQL is listening

sudo ss -tlnp | grep 5432

Expected output shows postgres listening on 127.0.0.1:5432 or 0.0.0.0:5432.

3. Check the listen address configuration

sudo grep listen_addresses /etc/postgresql/*/main/postgresql.conf

For remote connections, set:

listen_addresses = '*'

Then restart:

sudo systemctl restart postgresql

4. Check pg_hba.conf for access rules

sudo grep -v '^#' /etc/postgresql/*/main/pg_hba.conf | grep -v '^$'

5. Connect via Unix socket as a fallback

sudo -u postgres psql

FAQ

How do I check if PostgreSQL is running on a non-default port?
Run sudo ss -tlnp | grep postgres to see all listening PostgreSQL processes. The default port is 5432, but you can change it in postgresql.conf with the port directive.
What does 'could not connect to server: No such file or directory' mean?
This variant means psql attempted a Unix socket connection but the socket file does not exist. Use psql -h /var/run/postgresql or check the unix_socket_directories setting.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro