【发布时间】:2019-05-16 07:55:48
【问题描述】:
我有 .NET Core 控制台应用程序在 docker 中运行,我想连接到本地 MSSQL 数据库(不是 dockerized!),但我无法这样做。通过 IP 连接到远程服务器上的数据库可以正常工作,但是使用像 Data Source=DESKTOP-9DRU731;Initial Catalog=DB;User id=user;password=password; 这样的连接字符串会给我一个错误
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
有什么办法吗?
我已经尝试在 dockerfile 中添加暴露并在 docker compose 中为端口 1433 添加端口映射,以及将网络设置为主机。我的数据库启用了远程访问,当我在连接字符串中包含主机 IP 和端口时,我能够连接到它,但要求连接字符串保持不变。我也尝试过使用host.docker.internal,但还是没有运气。我认为其中一些可能会由于我使用的环境而失败,即:
- Win 10 Home(这意味着使用 Docker Toolbox,而不是 Docker for Windows)
- Linux 容器
我也尝试使用桥接网络,但在这种情况下,当我尝试连接到数据库时,我什至无法到达该部分,就像之前我尝试创建服务总线队列一样,它因套接字异常而失败。
我的码头文件:
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"]
和码头工人撰写:
version: '3.4'
services:
app:
image: ${DOCKER_REGISTRY-}app
build:
context: .
dockerfile: app/Dockerfile
编辑
感谢@Mihai,有一个可能的解决方案。添加
extra_hosts:
- "DESKTOP-9DRU731:<your_host_ip>"
到 Dockerfile 工作。不幸的是,我正在寻找更通用的解决方案。
我将添加更多上下文 - 我在远程数据库中存储了近 100 个连接字符串。它们指向特定于外部应用程序实例的数据库。此数据库位于主机或主机的专用网络中,我需要使用此专用网络中的服务器名称或 IP 连接到它们。
【问题讨论】:
-
您是否尝试过使用主机 IP 地址而不是名称?
-
是的,它可以工作,但不幸的是我无法更改连接字符串。好吧,从技术上讲我可以,但我真的想避免这种情况。
标签: docker .net-core docker-compose dockerfile