我们有一个 ASP.NET Core 2.2 应用程序,它与托管在单独服务器上的后端数据库完美配合。所有 CRUD 操作都完美无缺。我们对应用程序进行了 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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
docker compose 文件看起来像下面的代码:
version: '3.4'
services:
services.webapi:
image: ${DOCKER_REGISTRY-}serviceswebapi
build:
context: .
dockerfile: Services.WebApi\Dockerfile
network: host
此配置中可能有什么问题阻碍应用程序与 SQL Server 实例通信?
更新 1:SQL Server 未 dockerized。
更新 2:应用程序从其 appsettings.json 文件中读取 SQL 连接字符串。这是重命名服务器名称和凭据后的连接字符串:
Server=WIN-MSSQL1\\MSSQLSERVER2017;Initial Catalog=ServiceDB;User ID=cruduser;Password=foo;Connect Timeout=60;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False
最佳答案
在正常情况下,您可以通过 composer 文件在容器的/etc/hosts 文件中添加 sql 主机名来修复,如下所示:
version: '3.4'
services:
services.webapi:
image: ${DOCKER_REGISTRY-}serviceswebapi
build:
context: .
dockerfile: Services.WebApi\Dockerfile
network: host
extra_hosts:
- "WIN_MSSQL1:192.168.0.1"
不幸的是由于这个issue在 composer 文件中添加 extra_hosts 是行不通的,我希望他们能尽快解决这个问题。
因此,为了让连接正常工作,请将主机名替换为 SQL 服务器的 ip 地址:
来自这里:
Server=WIN-MSSQL1\\MSSQLSERVER2017;Initial Catalog=ServiceDB;User ID=cruduser;Password=foo;Connect Timeout=60;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False
为此:
Server=192.168.0.1\\MSSQLSERVER2017;Initial Catalog=ServiceDB;User ID=cruduser;Password=foo;Connect Timeout=60;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False
关于c# - 无法从 docker 容器连接到 SQL Server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54008489/