Skip to content
Latchkey

ASP.NET Core "Npgsql.NpgsqlException ... Connection refused" in CI

Npgsql tried to open a connection and the OS refused it, meaning nothing is listening on that host and port yet. In CI this almost always means the Postgres service container is still starting when the app connects.

What this error means

The app or an integration test fails with "Npgsql.NpgsqlException (0x80004005): Failed to connect to 127.0.0.1:5432" and an inner "Connection refused" while the service container is booting.

.NET
Npgsql.NpgsqlException (0x80004005): Failed to connect to 127.0.0.1:5432
 ---> System.Net.Sockets.SocketException (111): Connection refused

Common causes

The database service is not ready yet

GitHub Actions marks a service container as up before Postgres finishes initializing, so the app connects during the gap and is refused.

Wrong host or port for the service

The connection string points at the wrong host (for example a container name vs localhost) or a port the service does not expose to the job.

How to fix it

Gate on a health check

Add a health check so the job waits until Postgres accepts connections before the app or tests run.

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

Retry the initial connection

Enable EF Core connection resiliency so a transient refusal during startup is retried rather than failing the job.

Program.cs
builder.Services.AddDbContext<AppDbContext>(o =>
    o.UseNpgsql(cs, npg => npg.EnableRetryOnFailure()));

How to prevent it

  • Add a service health check and wait for it before connecting.
  • Use localhost and the mapped port that matches the ports mapping.
  • Enable EnableRetryOnFailure for transient startup refusals.

Frequently asked questions

What causes ""Npgsql ... Connection refused""?
GitHub Actions marks a service container as up before Postgres finishes initializing, so the app connects during the gap and is refused.
How do I fix "Npgsql ... Connection refused"?
Add a health check so the job waits until Postgres accepts connections before the app or tests run.

Related guides

References

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