could not connect 🐘 PostgreSQL

PostgreSQL: could not connect to server / connection refused — Is the server running on host and accepting TCP/IP connections?

The client reached no PostgreSQL listener at that host/port — the server is down, listening elsewhere, or not accepting remote connections.

Seen on: PostgreSQL Linux Docker

Meaning

By default PostgreSQL listens only on localhost (listen_addresses = 'localhost') and port 5432. Remote clients also need a matching pg_hba.conf line and an open firewall port. In Docker, localhost means the app container itself.

Common causes

  • PostgreSQL service stopped or crashed (disk full, bad config after edit)
  • listen_addresses limited to localhost while connecting remotely
  • Different port (5433 when multiple versions are installed)
  • Firewall / cloud security group blocking 5432
  • Docker: using localhost instead of the service name
  • Socket path mismatch: “could not connect to server: No such file or directory … /var/run/postgresql/.s.PGSQL.5432”

⚡ Quick fix

  1. sudo systemctl status postgresql and read the log if it’s down
  2. Check SHOW listen_addresses; and SHOW port;
  3. Set listen_addresses = '*' + a pg_hba.conf host line for remote access, then restart
  4. In Docker Compose, connect to db:5432

Detailed fix by platform

Linux

  1. Check service, port and listeners:
    bash
    sudo systemctl status postgresql
    sudo ss -ltnp | grep postgres
    pg_lsclusters                      # Debian/Ubuntu: shows version, port, status
    sudo tail -n 50 /var/log/postgresql/postgresql-*-main.log

Docker

  1. DATABASE_URL=postgres://app:secret@db:5432/app — use the compose service name; add a healthcheck so the app waits for the DB.

How to diagnose

  1. Service — Running?
  2. Listener — Which address/port does it listen on?
  3. Network — Firewall / container network?
  4. Auth — Next error after connecting: pg_hba.conf?

🧠 Still stuck? Analyze your error

Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.