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

psql: could not connect to server: Connection refused

DodaTech 2 min read

The PostgreSQL error “could not connect to server: Connection refused” means psql could not establish a TCP connection to the PostgreSQL server. The database service is either not running, not listening on the expected address, or blocking the connection.

What It Means

The client attempted to connect to a PostgreSQL instance but the server rejected the connection at the transport level. No PostgreSQL process is accepting connections on the specified host and port.

Why It Happens

  • The PostgreSQL service is stopped or failed to start.
  • PostgreSQL is listening only on localhost but you connected via the external IP.
  • The pg_hba.conf file does not permit the connection.
  • Another process is blocking port 5432.
  • 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 in postgresql.conf

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

To accept remote connections, set:

listen_addresses = '*'

Then restart:

sudo systemctl restart postgresql

4. Configure pg_hba.conf

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

Add a line for your user or network:

# Allow local user
local   all             myuser                          md5
# Allow local TCP
host    all             myuser          127.0.0.1/32    md5
# Allow network
host    all             myuser          192.168.1.0/24  md5

5. Manually connect via Unix socket

sudo -u postgres psql

FAQ

How do I find which port PostgreSQL is running on?
Run sudo ss -tlnp | grep postgres or psql -p 5432 -h localhost -U postgres -c "SHOW port;". The default port is 5432.
What does 'could not connect to server: No such file or directory' mean?
This variant means psql tried a Unix socket that does not exist. Specify the socket directory with psql -h /var/run/postgresql or check unix_socket_directories in postgresql.conf.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro