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.
Npgsql.NpgsqlException (0x80004005): Failed to connect to 127.0.0.1:5432
---> System.Net.Sockets.SocketException (111): Connection refusedCommon 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.
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=10Retry the initial connection
Enable EF Core connection resiliency so a transient refusal during startup is retried rather than failing the job.
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.