Kira Resari
Kira Resari

Reputation: 2420

Connecting to SQL Database in Docker instance from C# fails

I have a C# program which I want to connect to a simple Dockerized SQL Server database on Windows. The docker-compose.yml for the database looks like this:

version: "3.9"
services:
    db:
        image: "mcr.microsoft.com/mssql/server"
        environment:
            SA_PASSWORD: "*****"
            ACCEPT_EULA: "Y"

Now I am trying to connect to it in C# like this:

SqlConnection connection = new SqlConnection(@"Server=db;Database=master;User=sa;Password=*****;");
connection.Open();

At connection.Open() it fails with this error:

System.Data.SqlClient.SqlException: [...]
System.ComponentModel.Win32Exception: The Network Path could not be found

It seems obvious to me that the problem is the connection string. However, I have searched and searched and wasn't able to figure out what the correct connection string in this case would be. Can someone please help me out?


EDIT:

I now also tried this connection string:

@"Server=localhost,1433;Database=master;User=sa;Password=*****;"

This result in the following, different error:

System.ComponentModel.Win32Exception: The Remote Host refused the network connection

Upvotes: 1

Views: 3015

Answers (1)

Kira Resari
Kira Resari

Reputation: 2420

I now figured out what the problem was.

The problem was that my docker-compose.yml was still missing the ports section. For some reason the tutorial from which I copied this didn't feature this section.

So here is how the docker-compose.yml needs to look:

version: "3.9"
services:
    db:
        image: "mcr.microsoft.com/mssql/server"
        environment:
            SA_PASSWORD: "*****"
            ACCEPT_EULA: "Y"
        ports:
            - "1433:1433"

After that, I am able to connect to the database from C# using the following connection string:

@"Server=localhost,1433;Database=master;User=sa;Password=*****;"

Upvotes: 1

Related Questions