I'm attempting to connect to a local SQL Server Express instance I have on my dev box.
I'm using the following code:
var cs = new System.Data.SqlClient.SqlConnectionStringBuilder();
cs.InitialCatalog = "dev_db";
cs.DataSource = @"(local)\SQLEXPRESS";
cs.IntegratedSecurity = false;
cs.ConnectTimeout = 5;
cs.Encrypt = false;
cs.UserID = "user";
cs.Password = "password";
var xpto = new System.Data.SqlClient.SqlConnection(cs.ConnectionString);
xpto.Open();
This works fine in a console or Windows app, but fails miserably when trying in a Web API project running in a Docker Desktop (configured as Linux).
The exact same code.
This is the exception thrown:
System.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.
(provider: TCP Provider, error: 25 - Connection string is not valid)
Has anyone encountered this problem and know how to solve it?
To preemptively answer questions:
I also followed this answer to configure SQL Server Express.
After reading this answer, I tried using
host.docker.internaland using the IP address of my dev box. Both tries yielded the same results.
// Attempt with host.docker.internal
cs.DataSource = @"host.docker.internal\SQLEXPRESS";
// Same error
// Attempt with dev box IP
cs.DataSource = @"192.168.15.3\SQLEXPRESS";
// Same error.
The instance of SQL Server Express is on the dev box, not in the Docker.
SQL Server Express is configured to allow remote connections:
Edited to add:
This is the Docker file:
#See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging.
FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build
WORKDIR /src
COPY ["TestProject.csproj", "."]
RUN dotnet restore "./TestProject.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "TestProject.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "TestProject.csproj" -c Release -o /app/publish /p:UseAppHost=false
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "TestProject.dll"]
Edited to add:
Connection with a PostgreSQL database was successful. Only SQL Server Express is giving me a headache.

SQLEXPRESSrunning on your docker container or it is on your local machine?-p realport:containerport?