我有一个 ASP.NET Core v3 Web API 服务。它可以正常运行并连接到普通的 Windows 托管 SQL Server 实例。但是当我尝试将它连接到 Docker Linux 托管的 SQL Server 实例时,它失败了。
以下是一些细节:
docker network inspect bridge -f "{{json .Containers }}"
它列出了两个容器。 这是我的数据库连接字符串:
"Server=localhost;Database=MyDatabase;User Id=MySqlUser;Password=MyPassword"
我也尝试在我的
hosts
中输入localsql 文件设置为 127.0.0.0。 localhost 和 localsql 都可以使用 SSMS 连接到 docker 数据库。这是实际的错误消息:
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: 40 - Could not open a connection to SQL Server)
当我尝试从我的主机文件中使用 localsql 时,它有一个内部异常,此消息
"Name or service not known"
最佳答案
连接字符串指向 localhost。容器中的 localhost 是指容器本身,因此 ASP.NET Core Container 会尝试在同一容器上查找 SQL Server。
在连接字符串中使用 SQL Server 容器的名称而不是 localhost。为了使其工作,您需要创建一个用户定义的网桥,两个容器都连接到该网桥:
docker network create sql-server-test
运行容器时,您需要指定容器连接到的网络,如下所示:
# Please note the --name and --network parameters
docker run -e ACCEPT_EULA=Y -e 'SA_PASSWORD=<PWD>' -d --name sql-server --network sql-server-test mcr.microsoft.com/mssql/server:2019-latest
# Please note the --network parameter
docker run -d -p 8889:80 --name aspnet-core --network sql-server-test aspnet-core
由于两个容器现在都连接到同一网络,您可以在连接字符串中使用 Sql Server 容器的名称(在同一个 sql-server 中),并使用此连接字符串连接到 Sql Server:
"Data Source=sql-server;Initial Catalog=master;User ID=sa;Password=<PWD>"
有关 Docker 网络的详细信息以及有关如何在容器之间设置通信的其他选项,请参阅此 link .
关于sql-server - ASP.NET Core Web API 服务无法连接到同一网络上的 Docker SQL Server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59461691/