I have .NET Core console app running in docker and I want to connect to local MSSQL database (not dockerized!), but I'm unable to do so. Connecting to DB on remote server by IP works fine, but using connection string like Data Source=DESKTOP-9DRU731;Initial Catalog=DB;User id=user;password=password; gives me an error
System.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: 35 - An internal exception was caught) ---> System.AggregateException: One or more errors occurred. (No such device or address) ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException: No such device or address
Is there any way to do this?
I have already tried adding expose in dockerfile and port mapping in docker compose for port 1433, as well as setting the network as host. My DB has remote access enabled and I am able to connect to it when I include host IP and port in connection string, but it is a requirement that connection string remains unchanged. I also tried using host.docker.internal, but again no luck. I think that some of it may fail due to environment which I'm using, which is:
- Win 10 Home (which means using Docker Toolbox, not Docker for Windows)
- Linux containers
I also tried using bridged network, but in that case I cannot even reach the part when I'm trying to connect to DB, as before that I'm trying to create Service Bus queue and it fails with socket exception.
My dockerfile:
FROM microsoft/dotnet:2.2-sdk AS build-env
WORKDIR /app
# Copy csproj and restore as distinct layers
COPY *.csproj ./
RUN dotnet restore
# Copy everything else and build
COPY . ./
RUN dotnet publish -c Release -o out
# Build runtime image
FROM microsoft/dotnet:2.2-runtime
WORKDIR /app
COPY --from=build-env /app/out .
ENTRYPOINT ["dotnet", "app.dll"]
And docker compose:
version: '3.4'
services:
app:
image: ${DOCKER_REGISTRY-}app
build:
context: .
dockerfile: app/Dockerfile
EDIT
Thanks to @Mihai there's a possible solution. Adding
extra_hosts:
- "DESKTOP-9DRU731:<your_host_ip>"
to Dockerfile works. Unfortunately I'm looking for more generic solution.
I'll add more context - I have nearly 100 connection strings stored in remote DB. They are pointing to databases specific for instances of an external app. This DBs are located on host or in host's private network and I need to connect to them using server name or IP from this private network.