Skip to content
Latchkey

psycopg2 "OperationalError: could not connect to server" in CI

psycopg2 tried to open a TCP connection to Postgres and failed - the host/port was wrong, the database service had not finished starting, or the network path was blocked. No query ever ran.

What this error means

A DB step fails with "psycopg2.OperationalError: could not connect to server: Connection refused" or "could not translate host name", often early in a job before the service is ready.

python
psycopg2.OperationalError: could not connect to server: Connection refused
    Is the server running on host "localhost" (127.0.0.1) and accepting
    TCP/IP connections on port 5432?

Common causes

The database service is not ready yet

The job connected before the Postgres service container finished initializing, so the port refuses the connection.

Wrong host, port, or service networking

The connection string points at localhost when the service is on a service-network hostname, or the port mapping differs in CI.

How to fix it

Wait for the database to accept connections

Add a health-check/wait loop so the job connects only once Postgres is ready.

.github/workflows/ci.yml
services:
  postgres:
    image: postgres:16
    options: >-
      --health-cmd pg_isready
      --health-interval 5s
      --health-retries 10

Use the correct host and port

Point the connection string at the service host and mapped port CI exposes.

Terminal
DATABASE_URL=postgresql://user:pass@localhost:5432/app

How to prevent it

  • Gate DB steps on a readiness/health check.
  • Use the service hostname and port CI actually exposes.
  • Add a short connect retry for service startup races.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →