{"record":{"id":"cd163c8ada1874aa","repo":"microsoft/aspire","slug":"could-not-open-connection-to-sqlserver-name","errorCode":null,"errorMessage":"Could not open connection to '{sqlServer.Name}'","messagePattern":"Could not open connection to '(.+?)'","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/Aspire.Hosting.SqlServer/SqlServerBuilderExtensions.cs","lineNumber":85,"sourceCode":"\n                          if (connectionString == null)\n                          {\n                              throw new DistributedApplicationException($\"ConnectionStringAvailableEvent was published for the '{sqlServer.Name}' resource but the connection string was null.\");\n                          }\n                      })\n                      .OnResourceReady(async (sqlServer, @event, ct) =>\n                      {\n                          if (connectionString is null)\n                          {\n                              throw new DistributedApplicationException($\"ResourceReadyEvent was published for the '{sqlServer.Name}' resource but the connection string was null.\");\n                          }\n\n                          using var sqlConnection = new SqlConnection(connectionString);\n                          await sqlConnection.OpenAsync(ct).ConfigureAwait(false);\n\n                          if (sqlConnection.State != System.Data.ConnectionState.Open)\n                          {\n                              throw new InvalidOperationException($\"Could not open connection to '{sqlServer.Name}'\");\n                          }\n\n                          foreach (var sqlDatabase in sqlServer.DatabaseResources)\n                          {\n                              await CreateDatabaseAsync(sqlConnection, sqlDatabase, @event.Services, ct).ConfigureAwait(false);\n                          }\n                      });\n    }\n\n    /// <summary>\n    /// Adds a SQL Server database to the application model. This is a child resource of a <see cref=\"SqlServerServerResource\"/>.\n    /// </summary>\n    /// <ats-summary>Adds a SQL Server database resource</ats-summary>\n    /// <param name=\"builder\">The SQL Server resource builders.</param>\n    /// <param name=\"name\">The name of the resource. This name will be used as the connection string name when referenced in a dependency.</param>\n    /// <param name=\"databaseName\">The name of the database. If not provided, this defaults to the same value as <paramref name=\"name\"/>.</param>\n    /// <returns>A reference to the <see cref=\"IResourceBuilder{T}\"/>.</returns>\n    /// <ats-returns>The resource builder.</ats-returns>","sourceCodeStart":67,"sourceCodeEnd":103,"githubUrl":"https://github.com/microsoft/aspire/blob/25830f84bd145686607ad00c057b3f84e2e51d43/src/Aspire.Hosting.SqlServer/SqlServerBuilderExtensions.cs#L67-L103","documentation":"Aspire's AddSqlServer registers a callback that runs when the SQL Server container resource is healthy: it opens a real SqlConnection to the server and then creates any child database resources. This DistributedApplicationException is thrown when the connection could not reach the Open state despite OpenAsync not throwing, meaning the server is reachable at the socket level but not accepting/validating SQL logins.","triggerScenarios":"Calling builder.AddSqlServer(...).AddDatabase(...) and the health-check callback fires, SqlConnection.OpenAsync returns but State != Open — typically an authentication failure, TLS negotiation failure, or the server reported an error without raising during OpenAsync.","commonSituations":"Wrong or missing SA password / password not yet applied to the container; container listening but SQL Server still initializing after health check passed; TLS/cert trust issues between client and container; connection string referencing wrong host or port after endpoint remapping.","solutions":["Verify the container is fully started (check docker logs for 'SQL Server is now ready for client connections') before the callback runs","Confirm the SA_PASSWORD / password parameter matches what the container was created with and satisfies SQL Server password policy","Check the connection string host/port matches the container's actual assigned endpoint (use the resource's endpoint, not a hard-coded port)","Try connecting manually with sqlcmd or a SQL client using the same connection string to see the underlying failure","Add connection retry logic; transient states during container startup can produce a non-Open final state"],"exampleFix":"// before\nvar sqlserver = builder.AddSqlServer(\"sql\").AddDatabase(\"db\");\n// after - ensure a stable, valid password and rely on resource wait\nvar sqlserver = builder.AddSqlServer(\"sql\", password: builder.Configuration[\"SqlPassword\"])\n    .WithLifetime(ContainerLifetime.Persistent)\n    .AddDatabase(\"db\");","handlingStrategy":"validation","validationCode":"// before relying on the resource, wait for health and verify connectivity\nawait app.ResourceNotifications.WaitForResourceHealthyAsync(\"sql\");\nvar cs = await sqlDatabaseResource.ConnectionStringExpression.GetValueAsync(ct);\nif (cs is null) throw new InvalidOperationException(\"Connection string not yet available\");\nusing var conn = new SqlConnection(cs);\nawait conn.OpenAsync(ct); // surface the real auth/TLS error early","typeGuard":null,"tryCatchPattern":"try\n{\n    await sqlConnection.OpenAsync(ct);\n}\ncatch (SqlException ex)\n{\n    // inspect ex.Number: 18456 = login failed, -1 = timeout/network\n    logger.LogError(ex, \"SQL Server connection failed (error {Number})\", ex.Number);\n    throw;\n}","preventionTips":["Use WithLifetime(ContainerLifetime.Persistent) and wait for resource healthy before connecting","Always set an explicit, policy-compliant SA password; never rely on defaults","Use the resource's assigned endpoint instead of hard-coded ports","Test the connection string manually with sqlcmd when the container starts failing"],"tags":["sqlserver","connection","containers","startup"],"backgroundTag":"connection-refused","analyzedSha":"25830f84bd145686607ad00c057b3f84e2e51d43","analyzedAt":"2026-09-16T11:10:06.193Z","contentChangedAt":"2026-09-16T11:10:06.193Z","schemaVersion":2},"datasetVersion":"2026-09-21T09:17:21.228Z"}