.NET Core Web API Application cannot connect to SQL server running on Docker

别来无恙 提交于 2021-02-11 14:49:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!