You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mac本地Docker SQL数据库无法被Parallels Windows虚拟机连接

问题描述

连接SQL Server时抛出错误:

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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)'

环境配置

  • MacBook M2 Pro芯片设备
  • Mac本地通过Docker运行SQL Server,使用Azure Data Studio管理
  • Parallels虚拟机(Windows系统)中运行Visual Studio编写代码

测试代码

using Dapper;
using SQLlessions.Models;
using System.Data;
using System.Data.SqlClient;

namespace SQLlessions
{
    internal class Program
    {
        public static void Main(string[] args)
        {
            // 1 - connect to sql database

            string connectionString = "Server = localhost; Database = DotNetCourseDatabase; Trusted_Connection = false; TrustServerCertificate = true; User Id = **; Password = *******;";

            IDbConnection dbConnection = new SqlConnection(connectionString);
            
            // 2 - test the connection works

            string sqlCommand = "SELECT GETDATE()";

            DateTime rightNow = dbConnection.QuerySingle<DateTime>(sqlCommand);

            Console.WriteLine(rightNow);
        }
    }
}
解决步骤

1. 替换连接字符串中的localhost为Mac实际IP

Parallels虚拟机内的Windows无法通过localhost直接访问Mac宿主的Docker服务,需使用Mac本地IP:

  • 在Mac终端执行 ipconfig getifaddr en0 获取当前网卡IP(如192.168.3.10)
  • 修改连接字符串的Server字段,同时指定SQL Server默认端口1433:
    Server = 192.168.3.10,1433; Database = DotNetCourseDatabase; Trusted_Connection = false; TrustServerCertificate = true; User Id = sa; Password = 你的密码;
    

2. 确认Docker容器端口映射

检查SQL Server容器是否正确映射1433端口到Mac宿主:

  • 终端执行 docker ps,查看容器的PORTS列是否显示 0.0.0.0:1433->1433/tcp
  • 若未映射,重新启动容器时添加端口参数:
    docker run -e "ACCEPT_EULA=Y" -e "SA_PASSWORD=你的强密码" -p 1433:1433 --name sqlserver -d mcr.microsoft.com/mssql/server:latest
    

3. 调整Parallels网络模式

将Windows虚拟机的网络设置为桥接网络,确保和Mac处于同一局域网:

  • 打开Parallels Desktop,选中Windows虚拟机 → 右上角「设置」→ 「网络」→ 选择「桥接网络」,并关联Mac当前使用的网卡(如Wi-Fi)

4. 验证虚拟机与Mac的连通性

在Windows虚拟机的命令提示符中执行:

ping 你的MacIP地址

若ping不通,检查Mac防火墙设置:

  • 打开Mac系统设置 → 「网络」→ 「防火墙」→ 「选项」,确保未阻止Docker相关连接,或添加允许1433端口入站的规则

5. 确认SQL Server远程连接配置

通过Azure Data Studio检查:

  • 连接Docker中的SQL Server → 右键服务器 → 「属性」→ 「连接」,确认「允许远程连接到此服务器」已勾选
  • 右键服务器 → 「属性」→ 「安全性」,确认身份验证模式为「SQL Server和Windows身份验证模式」,修改后重启容器:docker restart sqlserver

6. 核对账号密码正确性

确保连接字符串中的User Id为sa(Docker SQL Server默认管理员账号),密码与启动容器时设置的SA_PASSWORD完全一致,无拼写错误

内容的提问来源于stack exchange,提问作者kevin espina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 08:08:12