c# - 无法从 docker 容器连接到 SQL Server

标签 c# sql-server docker asp.net-core docker-compose

我们有一个 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/

相关文章:

c# - Swagger for Asp.Net Mvc 网站

c# - 使用 C# 将鱼眼图像转换为风景并将其分为四个部分

sql-server - SQL动态查询: check whether table column has any data

ubuntu - 同一网络中的 docker 容器无法到达同一网络中的其他容器

performance - 在 EC2 实例内运行的 docker 容器内运行的 Web 服务器响应非常缓慢

c# - Dictionary<> 总是按值排序,从键查找索引

c# - 一个后台工作线程和多个进度条

sql - 无法在 SQL 中创建程序集

c# - 将单个值从存储过程返回到 .Net : OUTPUT parameter or ExecuteScalar? 有什么更好的

node.js - 使用 docker 和 docker compose 访问 typescript 中的 Node 模块