sql-server - 无法通过Web API .NET Core连接到SQL Server Docker容器

标签 sql-server docker .net-core

我试图通过使用.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服务器上时,它可以正常运行。

最佳答案

如果要在同一台计算机上链接两个docker容器,则有三个选项:

  • 使用 docker-compose
  • 使用--network运行图像
  • 高级场景: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

    关于sql-server - 无法通过Web API .NET Core连接到SQL Server Docker容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63910756/

    相关文章:

    asp.net-core - project.json 版本控制格式

    .net-core - System.Runtime 4.2.1.0 构建 v2 Azure Functions 项目的 FileNotFoundException

    sql-server - 将具有多个内部连接的 sql 查询转换为 LINQ

    c# - SQL Server数据库专项查询

    linux - docker容器奇怪的文件权限(权限位和用户位的问号)

    docker - 如何使用 Ansible 启动 Docker 容器

    .net-core - 多个 api 版本的单个客户端

    php - 由于单引号无法将字符串插入数据库

    sql - SQL Server 中的多个子句,其中所有列都不等于零

    docker - 在 Alpine Linux上安装miniconda失败