问题
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"
Using .NET Core 3.1. The Web API is running in a container
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();
Any ideas?
EDIT
So, tried with the ip of the container "Server=172.17.0.2,1433;..." but the error persists.
EDIT2 - Solution
So, the docker-compose solved the issue, inserted the settings for slq running in docker.
回答1:
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
来源:https://stackoverflow.com/questions/60909456/net-core-web-api-application-cannot-connect-to-sql-server-running-on-docker