【问题标题】:Can't connect to SQL Server Docker Container through Web API .NET Core无法通过 Web API .NET Core 连接到 SQL Server Docker 容器
【发布时间】:2021-01-02 17:41:03
【问题描述】:

我正在尝试通过另一个使用 .NET Core 3.1 构建的容器化应用程序(微服务)连接到 Docker 映像 SQL Server 数据库,但我收到 Docker 引发的以下错误:

fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]

An error occurred using the connection to database 'ProductDb' on server 'localhost,1433'.

fail: Microsoft.EntityFrameworkCore.Query[10100]

An exception occurred while iterating over the results of a query for context type 'Infrastructure.ProductContext'.

Microsoft.Data.SqlClient.SqlException (0x80131904): 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)

我使用的连接字符串是:

"ProductDb": "Server=localhost,1433;Database=ProductDb;User Id=sa;Password=********;"

我需要提到的是,当它托管在 IIS 服务器上时,同样的应用程序可以正常工作。

【问题讨论】:

  • 如果将localhost,1433 替换为.,1433 会发生什么? 1433 甚至是必要的,因为它是 SQL Server 的默认端口。

标签: sql-server docker .net-core


【解决方案1】:

如果您想链接同一台机器上的两个 docker 容器,您有以下三种选择:

  1. 使用docker-compose
  2. --network运行镜像
  3. 高级场景:Docker Swarm / Kubernetes

您的问题:
您的容器未链接并且(我想您没有使用 docker-compose 或 --network 开关运行它)您还指定了 localhost 其中 localhost 指的是同一台机器,在这种情况下是 ASP .NET Core 容器实例。

使用 docker-compose(首选且简单)或--network 并使用Server=container_name\instancename_ifany,1433 指定连接字符串

当您运行 SQL 映像时,您可以选择将 1433 端口重定向到另一个端口并检查/监视 sql 实例 --ports 9001:1433;有了这个,你可以使用 SSMS 并连接到localhost, 9001

【讨论】:

  • 非常感谢,docker-compose 解决方案对我来说很好,问题出在我的连接字符串中,我必须将 localhost 更改为我的数据库容器名称。
  • 很高兴为您提供帮助。标记为答案。
【解决方案2】:

定位容器名称而不是 localhost。本地主机将尝试连接到自身(容器)。

【讨论】:

    猜你喜欢
    • 2020-01-11
    • 2017-06-07
    • 1970-01-01
    • 2019-07-10
    • 2021-12-15
    • 2019-05-29
    • 2016-12-26
    • 2020-11-20
    • 1970-01-01
    相关资源
    最近更新 更多