我试图通过使用.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
你的问题:
您的容器未链接,并且(我想您没有使用
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/