.NET, DockerFile and ConnectionString

39 views Asked by At

I have a .NET 7 web application, and I have added Docker support. The application uses appsettings.{environment}.json for settings, and my connection string is in there (for now, at least). I'm relatively new to docker, and I am not sure if its a docker thing, or the way VS loads my container or if its my code/project setup.

After Visual Studio generated the Dockerfile for me, it appears to build and spin up the container. However it fails to connect to the SQL Server.

I have Docker and SQL server running on the same machine. SQL Server is open to remote connections, and is enabled for TCP/IP and Named Pipes.

The connection string looks like this and works fine if I run the project natively in VS.

  "ConnectionStrings": {
    "RackEmAppDB": "Data Source=HOSTNAME\\dev,1433;Initial Catalog=MY_DB_NAME;User ID=MY_SQL_USERID;Password=MY_PASSWORD;"
  },

And it is loaded into the app in Startup.cs

services.AddDbContext<ApplicationDbContext>(options =>
{
    options.UseSqlServer(Configuration.GetConnectionString("RackEmAppDB"));
});

The error received when running through docker though is

Microsoft.Data.SqlClient.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. 

Which indicates an issue with connectivity to the server instance.

Launchsettings.json looks like this - I added the reference to the correct appsettings file after some googling, but it hasn't helped.

"Container (Dockerfile)": {
  "commandName": "Docker",
  "launchBrowser": true,
  "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/",
  "environmentVariables": {
    "ASPNETCORE_URLS": "https://+:443;http://+:80"
  },
  "publishAllPorts": true,
  "useSSL": true,
  "DockerfileRunArguments": "-e ASPNETCORE_ENVIRONMENT=Development"
}

What have I got wrong? I suspect I have overthought this now and it'll be something super basic but the solution eludes me.

1

There are 1 answers

1
Matthew Warr On

Through pure trial and error, I Identified that although I had 2 separate SQL instances, both were running on port 1433.

I had to change the SQL Port in configuration manager to something unique and target that in tyhe connection string. That, alongside the change to use host.docker.internal\\{INSTANCENAME} (which i had tried and had failed prior to the comment from Guru Stron) allowed the connection to be established.

I also had to enable the SQL Browser service.

So it appears Docker is ignoring anything relating to the instance name passed and only looking at the host and the port.