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.
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.
until pg_isready -h "$PGHOST" -p "$PGPORT"; do sleep 1; done
python manage.py migrateMatch the host to your CI network
- When Postgres is a container reachable on the runner, use
localhostwith a published port, or the service hostname on a container network. - Confirm the port is the one the service actually exposes.
- 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.