将docker容器中的Connectionstring连接到主机中的SQL Server dblocal

我们有一个运行在linux docker容器中的webserver。 当我在Windows 10主机上运行它时,在连接到本地SQL Server时出现以下错误:

Microsoft.EntityFrameworkCore.Query.Internal.SqlServerQueryCompilationContextFactory[1] An exception occurred in the database while iterating the results of a query. System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 25 - Connection string is not valid) ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException: No such device or address... 

json中的连接string如下所示:

 "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=MyAppDb;User ID=test;Password=test;", 

当我用相同的连接string在Visual Studio中debuggingWeb服务器时,它工作。 所以我不明白,为什么docker将抛出Connection string is not valid错误。

networking服务器使用.NET Core 1.1,因此关于连接到SQL Server的命名实例应该起作用。 我有两个SQL Server实例安装。 与命名pipe道的连接将不起作用,因为Linux泊坞窗不支持它。

我使用容器的networking模式主机,所以它应该有与主机相同的networking环境:

 docker run --rm -it --name MyApp -vc:\users\myself\MyApp.json:/app/appsettings.json --network="host" MyAppImage 

有没有人有一个想法?

我使用容器的networking模式主机,所以它应该有与主机相同的networking环境

如果我正确地理解了这个陈述,这不会做你认为的事情。 容器与主机具有相同的networking环境。 但是, 主机不是您的物理机器,而是Docker创build的用于运行Linux容器的虚拟机。 这里有一个更全面的Hyper-Vnetworking解释。 下图是基于那篇文章的

在网络上的Docker

红色的网卡是您的计算机用来连接到Windows创build的虚拟交换机Docker的网卡。 用蓝色表示的网卡是linux VM用来连接到同一个虚拟交换机的网卡。 这也是您的容器在使用主机networking时看到的卡。

当您的应用程序在容器中运行时,您需要通过networking连接到数据库。 本文讨论在Windows上使用Docker Compose构build多容器应用程序。 尽pipe作者正在使用Windows容器,但他提供了一个示例docker-compose文件 ,该文件创build数据库容器以及用于将它们链接在一起的Web容器和连接string。

dockerizing NerdDinner应用程序还有一个很好的一步一步的演练。 第2部分将使用localdb将应用程序转换为集装箱式SQL Server。