Skip to content
Latchkey

FastAPI "sqlalchemy.exc.OperationalError: connection refused" in CI

SQLAlchemy tried to open a connection and the database refused it. In CI this almost always means the test database service is not defined, not healthy yet, or the connection URL points at a host or port nothing is listening on.

What this error means

Tests that touch the DB fail with "sqlalchemy.exc.OperationalError: (psycopg.OperationalError) connection to server ... failed: Connection refused" while pure unit tests pass.

python
sqlalchemy.exc.OperationalError: (psycopg.OperationalError) connection to server
at "localhost" (127.0.0.1), port 5432 failed: Connection refused
    Is the server running on that host and accepting TCP/IP connections?

Common causes

No database service in the CI job

The workflow does not define a Postgres (or other) service container, so nothing listens on the port the app connects to.

Tests run before the service is healthy

The database container is starting but not yet accepting connections when the first test connects.

How to fix it

Add a database service with a healthcheck

Define the DB as a service container and wait on its health so connections succeed.

.github/workflows/ci.yml
services:
  postgres:
    image: postgres:16
    env:
      POSTGRES_PASSWORD: postgres
      POSTGRES_DB: test
    ports: ['5432:5432']
    options: >-
      --health-cmd "pg_isready -U postgres" --health-interval 10s
      --health-timeout 5s --health-retries 5

Point the app at the service via env

Set the database URL to the service host and port used by the runner.

.github/workflows/ci.yml
env:
  DATABASE_URL: postgresql+psycopg://postgres:postgres@localhost:5432/test

How to prevent it

  • Define the test database as a service container with a healthcheck.
  • Wait for the service to be healthy before running tests.
  • Set the connection URL from CI env, not a hard-coded local default.

Related guides

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