Docker 和 EF Core:无法建立连接,因为目标机器主动拒绝

Docker and EF Core: No connection could be made because the target machine actively refused it

我尝试从 Docker 容器(运行ning .NET带有 EF Core 的核心应用程序)。

SQL 服务器配置为侦听默认端口 1433(未使用动态端口)并允许远程连接 (TCP/IP)。我还为防火墙和给定端口设置了入站规则(我也尝试关闭防火墙)。我可以在 Docker 容器中使用 sqlcmd 命令行工具 运行ning 连接到数据库和 运行 SQL 查询。

这是我正在使用的连接字符串:

Server=tcp:host.docker.internal,1433;Database=AuthIdentity;Trusted_Connection=False;User Id=sa;Password=xxxx;MultipleActiveResultSets=True;

当我 运行 我的容器时,我收到以下错误:

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: 0 - No connection could be made because the target machine actively refused it.)

当我关闭防火墙时(即使 SQL 端口有防火墙规则)我最终会得到:

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: TCP Provider, error: 0 - A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.)

当我启动与 IIS 应用程序相同的程序(没有任何其他更改)时,它 运行 非常好并且按预期连接。

程序执行第一个 SQL 操作时发生错误(在本例中是数据库迁移 - 这是在程序启动内)

serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>().Database.Migrate();

编辑:另一个API项目中的更简单设置(两者都会引发与上述相同的错误):

    [HttpGet("setup")]
    [AllowAnonymous]
    public IActionResult Setup()
    {
        try
        {
            this._context.Database.Migrate();
            return Ok("success");
        }
        catch (Exception e)
        {
            return Json(e);
        }

    }

    [HttpGet("get")]
    [AllowAnonymous]
    public List<ApplicationUser> Get()
    {
        return this._context.Users.ToList();
    }

编辑 2:根据@Mohsin Mehmood 的建议,我 运行 使用 NAT 地址(来自 ipconfig /all)进行测试,我可以使用给定的 IP (172.28.112.1) 成功连接到 SQL 服务器。我还检查了 运行ning docker run --rm -i microsoft/nanoserver:1709 ping host.docker.internal 时收到的内容,它让我 62.138.239.45 作为地址。

尽管如此,我还是很欣赏不使用 "hard-coded" IP 地址而是使用像 host.docker.internal 这样的 DNS 的解决方案。我也不确定为什么两个 IP 地址不同(172.28.112.162.138.239.45)以及为什么容器无法从 DNS 获取正确的地址。


我错过了什么?如何解决这个问题?我已经搜索了 Google 和 SO,但没有任何有效的答案。

我建议尝试 Windows 10 主机服务器 IP 地址而不是域 host.docker.internal 以确认问题与 DNS 解析有关。另外,我发现 windows containers

中还有一个 open issue related to internal host dns resolution