nPcomp
nPcomp

Reputation: 9843

Cannot connect Docker MsSql from AspNetCore app

I am trying to access Docker MsSql instance from my Aspnet Core app.

When I try from Management Studio, I can connect to the MsSql server. However, when I try to run the app, I get the following error message.

SqlException: 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)

Here is the connection string I am using from config.json

{ "ConnectionStrings": { "MyConnectionString": "Data Source=127.0.0.1;Initial Catalog=Test;Integrated Security=False;Persist Security Info=True;User ID=SA;Password=##someStrongPass~~;" } }

Upvotes: 2

Views: 837

Answers (2)

Mselmi Ali
Mselmi Ali

Reputation: 1257

You can also use the container name instead of the 127.0.0.1,port or localhost,port

{
  "ConnectionStrings": {
    "MyConnectionString": "Data Source=SQL_CONTAINER_NAME;Initial Catalog=Test;Integrated Security=False;Persist Security Info=True;User ID=SA;Password=SomeStrongPass;"
  }
}

Upvotes: 1

nPcomp
nPcomp

Reputation: 9843

I found the solution.

If anyone is running their AspNetCore app from the container and using a second container for the database instance. Make sure you use the host machine IP in the connection string and expose database port from the DB container. Unlike the containers on Linux, Docker containers on windows could not connect to the DB container's IP address directly. Hopefully, that can be addressed in the future releases.

So in this case, the connection string should be

{ "ConnectionStrings": { "MyConnectionString": "Data Source=YOURMACHINEsIP;Initial Catalog=Test;Integrated Security=False;Persist Security Info=True;User ID=SA;Password=SomeStrongPass;" } }

Upvotes: 1

Related Questions