1

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.

1
  • What happens if you replace localhost,1433 with .,1433? And is the 1433 even necessary as that is SQL Server's default port. Commented Sep 16, 2020 at 5:01

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much, the docker-compose solution woks fine for me , the problem was in my connection string I had to change localhost to my db container name.
Glad to help you. Mark as the answer.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.