Skip to content
Latchkey

Postgres "could not connect to server: Connection refused" in CI

The libpq-based driver (used by many language clients) reports "could not connect to server: Connection refused". The TCP connect was rejected - Postgres is not listening on that host/port yet, or the address is wrong. It is reachability, not authentication.

What this error means

Any libpq client (Python, Go, Node pg, etc.) fails at connect time with "could not connect to server: Connection refused", naming host 127.0.0.1 or the service name and port 5432. It often clears on retry once the database is up.

psql
could not connect to server: Connection refused
	Is the server running on host "127.0.0.1" and accepting
	TCP/IP connections on port 5432?

Common causes

Database not accepting connections yet

In CI the database is commonly a service that has not finished starting when the client connects, so the connect is refused.

Wrong host for the network topology

Using localhost/127.0.0.1 when Postgres runs as a service container reachable only by its service name (or vice versa) refuses every attempt.

Port not mapped or exposed

If the service port is not published on the runner network, the client connects to a closed port and is refused.

How to fix it

Wait for readiness, then connect

Poll until Postgres answers before the first client connection.

Terminal
until pg_isready -h "$PGHOST" -p "$PGPORT"; do sleep 1; done
python manage.py migrate

Match the host to your CI network

  1. When Postgres is a container reachable on the runner, use localhost with a published port, or the service hostname on a container network.
  2. Confirm the port is the one the service actually exposes.
  3. Retry once the service is healthy to confirm a transient cause.

How to prevent it

  • Pin the host/port to the CI network topology and keep it identical across steps.
  • Always gate on a readiness check before connecting.
  • On managed runners (Latchkey), self-healing auto-retries transient failures such as a database that is briefly slow to accept connections.

Frequently asked questions

What causes ""could not connect to server: Connection refused""?
In CI the database is commonly a service that has not finished starting when the client connects, so the connect is refused.
How do I fix "could not connect to server: Connection refused"?
Poll until Postgres answers before the first client connection.
Can Latchkey fix this automatically?
Yes. Latchkey runs your GitHub Actions on managed runners that detect this failure, apply the fix, and retry the job automatically - self-healing is on by default.

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card