aymen matador
aymen matador

Reputation: 13

Can't connect to SQL Server Docker Container through Web API .NET Core

I am trying to connect to a Docker image SQL Server database through another containerized application (microservice) built with .NET Core 3.1 but I get the following error thrown by Docker:

fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]

An error occurred using the connection to database 'ProductDb' on server 'localhost,1433'.

fail: Microsoft.EntityFrameworkCore.Query[10100]

An exception occurred while iterating over the results of a query for context type 'Infrastructure.ProductContext'.

Microsoft.Data.SqlClient.SqlException (0x80131904): 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)

The connection string I am using is:

"ProductDb": "Server=localhost,1433;Database=ProductDb;User Id=sa;Password=********;"

I need to mention that this same application works fine when it's hosted on a IIS server.

Upvotes: 1

Views: 1698

Answers (2)

user6316291
user6316291

Reputation: 91

Target the container name as opposed to localhost. Localhost will try to connect to itself (container).

Upvotes: 1

Max
Max

Reputation: 7100

If you want to link two docker containers on the same machine you have three options:

  1. Use docker-compose
  2. run image with --network
  3. Advanced scenario: Docker Swarm / Kubernetes

Your question:
Your containers is not linked and (I suppose you don't have run its with docker-compose or --network switch) you have also specified localhost where localhost refer to the same machine, in this case ASP.NET Core container instance.

Use docker-compose (preferred and simple) or --network and specify the connection string with Server=container_name\instancename_ifany,1433

When you run the SQL image you can optionally redirect 1433 port to another and check / monitor the sql instance --ports 9001:1433; with this you can use SSMS and connect to localhost, 9001

Upvotes: 1

Related Questions