0
votes

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
Is the .NET Core app also running in a container? What does docker ps -a show? - superstator
yes, also in a container 0.0.0.0:22443->443/tcp - Taras Rohovets
How are you making that link? Basically, localhost doesn't mean what you think it means in a container. You need to be able to resolve the other container by name, and reference that in your connstring - superstator
can you connect to the container using SSMS? - Luis Becerril
"Server=172.17.0.2,1433;..", so, tried with the ip of the container but the error persists... - Taras Rohovets

1 Answers

0
votes

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