macOS下Docker化.NET应用连接SQL Edge容器报错(0x80131904)求助
Docker化.NET应用无法连接SQL Server容器(macOS环境)
问题背景
在macOS系统上使用Rider和Docker开发.NET应用,数据库采用sqledge Docker镜像。本地运行服务时请求响应正常,但将.NET应用容器化后出现数据库连接错误。
错误日志
An error occurred using the connection to database 'FundraiserAPI' on server 'localhost'. fail: Microsoft.EntityFrameworkCore.Query[10100] An exception occurred while iterating over the results of a query for context type 'Raiserflow.CampaignOrgAPI.DbContext.FundraiserDbContext'. Microsoft.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: 40 - Could not open a connection to SQL Server: Could not open a connection to SQL Server)
当前连接字符串
"DefaultConnection": "Server=localhost;Database=FundraiserAPI;Initial Catalog=FundraiserAPI;User=sa;Password=123123;MultipleActiveResultSets=True;"
核心原因
容器内的localhost指向容器自身而非宿主机,导致.NET容器无法通过localhost访问SQL容器。另外sqledge镜像默认已启用TCP/IP协议,无需额外配置,问题核心是网络连通性配置错误。
解决方案
1. 使用自定义Docker网络(推荐)
Docker容器在同一自定义网络内可通过容器名直接通信,无需依赖宿主机IP:
- 创建自定义网络:
docker network create app-network - 启动SQL容器时加入该网络:
docker run -d --name sql-server --network app-network -p 1433:1433 -e SA_PASSWORD=123123 -e ACCEPT_EULA=Y sqledge/sqledge - 修改.NET应用的连接字符串,将
Server改为SQL容器的名称sql-server:"DefaultConnection": "Server=sql-server;Database=FundraiserAPI;Initial Catalog=FundraiserAPI;User=sa;Password=123123;MultipleActiveResultSets=True;" - 启动.NET容器时加入同一网络即可正常连接。
2. 使用宿主机IP替代localhost
- 在macOS终端执行以下命令获取宿主机IP:
ipconfig getifaddr en0 - 将连接字符串中的
localhost替换为获取到的IP(例如192.168.1.100):
注意:若宿主机IP动态变化,需手动更新连接字符串。"DefaultConnection": "Server=192.168.1.100;Database=FundraiserAPI;Initial Catalog=FundraiserAPI;User=sa;Password=123123;MultipleActiveResultSets=True;"
3. 使用Docker特殊域名(macOS专属)
Docker for Mac提供host.docker.internal域名,可直接映射到宿主机,无需手动获取IP:
- 修改连接字符串:
此方法适合开发环境快速调试,无需额外网络配置。"DefaultConnection": "Server=host.docker.internal;Database=FundraiserAPI;Initial Catalog=FundraiserAPI;User=sa;Password=123123;MultipleActiveResultSets=True;"
补充说明
sqledge镜像默认已开启TCP/IP协议并监听1433端口,无需在容器内额外配置。macOS无法使用SQL Server Configuration Manager不影响容器内的SQL Server运行,因为容器内的SQL Server是独立的运行实例。
内容的提问来源于stack exchange,提问作者mrhusky
相关产品推荐
相关产品推荐

