Docker容器中.NET 6应用无法通过本地VPN连接SQL Server的问题求助
大家好,我最近碰到了一个困扰很久的问题,想请教下各位大佬:
我有一个.NET 6的应用,需要连接到一台只有在VPN连接状态下才能访问的SQL Server。直接运行这个.NET应用的时候,数据库连接完全正常,但把它容器化之后,就死活连不上数据库了。
先给大家看看我的docker-compose配置:
version: '3.4' services: cronjob: image: ${DOCKER_REGISTRY-}cronjob build: context: . dockerfile: ../CronJob/Dockerfile environment: - DOTNET_ENVIRONMENT=Development
我的数据库连接字符串是这样写的:
var connectionStringSQL = $"Data Source={sql_data_source}; Initial Catalog = {sql_initial_catalog}; User Id = {sql_user_id}; password = {sql_password}; Encrypt = False; TrustServerCertificate = True";
这里补充个细节:只有使用命名实例格式(比如 databaseXX\YY)的时候,直接运行C#代码能正常连接;但容器化之后用这个格式,就会抛出如下错误:
Cannot connect to SQL Server Browser. Ensure SQL Server Browser has been started. at Microsoft.Data.SqlClient.SNI.SSRP.GetPortByInstanceName
如果我把连接字符串改成IP地址:端口的格式,又会出现另一个错误:
Microsoft.Data.SqlClient.SqlExceptionSystem.AggregateExceptionSystem.Net.Internals.SocketExceptionFactory+ExtendedSocketException", "message": "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.
我试过在docker-compose里加一些配置,想强制容器通过本地VPN访问数据库,比如:
- 添加
extra_hosts: - host.docker.internal:host-gateway - 设置
network_mode: "host"
但这两种方法都没起作用,还是会出现和之前一模一样的错误。
有没有大佬遇到过类似的问题?麻烦给指点下方向,谢谢啦!
备注:内容来源于stack exchange,提问作者hela masri

