.NET Core Web API应用程序无法连接到在Docker上运行的SQL Server [英] .NET Core Web API Application cannot connect to SQL server running on Docker
问题描述
使用MAC.错误(提供程序:TCP提供程序,错误:40-无法打开与SQL Server的连接).
Using MAC. Error (provider: TCP Provider, error: 40 - Could not open a connection to SQL Server).
Connection string "Data Source=localhost,1433;Initial Catalog=MyDatabase;Integrated Security=True;User id=sa;Password=MyPassword;MultipleActiveResultSets=true"
使用.NET Core 3.1.Web API在容器中运行
Using .NET Core 3.1. The Web API is running in a container
数据库正在docker容器上运行.映射的端口1433:1433能够从Azure Data Studio查询数据库.但是,当尝试从.net.core应用程序进行连接时,却在上面给了我这个错误.
The database is running on docker container. ports mapped 1433:1433 Able to query the database from Azure Data Studio. But while trying to connect from .net.core application it giving me that error above.
using System.Data.SqlClient;
SqlConnection connection = new SqlConnection(_connectionString);
connection.Open();
有什么想法吗?
编辑
因此,尝试使用容器"Server = 172.17.0.2,1433; ..."的ip,但是错误仍然存在.
So, tried with the ip of the container "Server=172.17.0.2,1433;..." but the error persists.
EDIT2-解决方案
因此,docker-compose解决了该问题,并插入了在docker中运行的slq的设置.
So, the docker-compose solved the issue, inserted the settings for slq running in docker.
推荐答案
通过名称引用容器.你可以做这样的事情
Reference the container by name. You could do something like this
sql-data:
environment:
- SA_PASSWORD=Pass@word
- ACCEPT_EULA=Y
ports:
- "5433:1433" # Important: In a production environment, you should be using a managed service
- ConnectionStrings__DefaultConnection=Server=sql-data;Database=MyDatabase;User Id=sa;Password=MyPassword;MultipleActiveResultSets=true
这篇关于.NET Core Web API应用程序无法连接到在Docker上运行的SQL Server的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!