ASP.NET Core SqlException "A network-related or instance-specific error" in CI
SqlClient could not reach the SQL Server instance. In CI this usually means the SQL Server service container has not finished starting, the connection string host or port is wrong, or TLS trust is not configured.
What this error means
The app or a test fails with "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible" (error 40 / provider: TCP Provider, error 0).
Microsoft.Data.SqlClient.SqlException (0x80131904): A network-related or
instance-specific error occurred while establishing a connection to SQL Server.
The server was not found or was not accessible. (provider: TCP Provider, error: 0)Common causes
SQL Server is still starting
The SQL Server image takes time to accept connections; the job connects during that window and fails.
Wrong host/port or missing TrustServerCertificate
The connection string uses the wrong host, or on newer SqlClient defaults, Encrypt=true fails without TrustServerCertificate=True against a dev cert.
How to fix it
Wait for SQL Server, then connect
- Start SQL Server with a strong SA password and wait until it is ready.
- Poll with
sqlcmd(or a health check) before running the app or tests. - Use
localhost,1433as the host in the connection string.
services:
sql:
image: mcr.microsoft.com/mssql/server:2022-latest
env:
ACCEPT_EULA: 'Y'
MSSQL_SA_PASSWORD: 'Your_strong_Pass1'
ports: ['1433:1433']Set TrustServerCertificate for dev/CI
Newer Microsoft.Data.SqlClient encrypts by default; trust the server cert in CI so the handshake succeeds.
Server=localhost,1433;Database=app;User Id=sa;Password=Your_strong_Pass1;TrustServerCertificate=TrueHow to prevent it
- Wait for SQL Server readiness before connecting.
- Set TrustServerCertificate=True (or configure trust) for CI connections.
- Enable connection resiliency so transient startup errors retry.