Dockerized .NET6 application throws Microsoft.Data.SqlClient.SqlException (0x80131904) error

Solution 1:

Microsoft.Data.SqlClient v2.0 and later use encryption by default if the server supports it.

This will cause problems if the server uses a certificate that isn't trusted by the server. In that case the exception will include a message (either directly or in an inner exception) saying that the server certificate isn't trusted. In this case you can add TrustServerCertificate=true to the connection string.

Another problem specific to containers is described in Unable to open connection to azure sql database from windows1809 container with Microsoft.Data.SqlClient 2.0.0: the container image may not have the Security.dll in C:\Windows\System32. In that issue the Nano image was used.

There's a relevant issue in the Windows Containers repo. It seems that at least the .NET 5 runtime base image doesn't have Security.dll.

One of the workarounds mentioned in the SqlClient issue is to copy the file there. Some of the comments in the linked issue show how to do this.

From the command line

docker cp C:\Windows\System32\security.dll container-name:/Windows/System32/security.dll

Or in the docker file

COPY --from=core /Windows/System32/security.dll /Windows/System32/security.dll

Another is to enable Managed networking on Windows which also removes the need for the Microsoft.Data.SqlClient.SNI binaries. To enable this set the following switch at startup :

AppContext.SetSwitch("Switch.Microsoft.Data.SqlClient.UseManagedNetworkingOnWindows", true);

The downside mentioned in the article is that

Managed SNI does not support non-domain Windows Authentication.