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.

asked on Stack Overflow Sep 15, 2020 by aymen matador • edited Sep 15, 2020 by Dale K

2 Answers


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

answered on Stack Overflow Sep 16, 2020 by Max

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

answered on Stack Overflow Sep 16, 2020 by user6316291

User contributions licensed under CC BY-SA 3.0