gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:38:07 28 4
gpt4 key购买 nike

我尝试从 Docker 容器(运行带有 EF Core 的 .NET Core 应用程序)连接到主机的 SQL Server 实例(SQL 2017 on Windows 10)。

SQL Server 配置为监听默认端口 1433(未使用动态端口)并允许远程连接 (TCP/IP)。我还为防火墙和给定端口设置了入站规则(我也尝试关闭防火墙)。我可以使用在 Docker 容器中运行的 sqlcmd 命令行工具连接到数据库并运行 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 服务器。我还检查了运行 docker run --rm -i microsoft/nanoserver:1709 ping host.docker.internal 时收到的内容,它让我得到 62.138.239.45 作为地址.

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


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

最佳答案

我建议尝试使用 Windows 10 主机服务器 IP 地址而不是域 host.docker.internal 来确认问题与 DNS 解析有关。另外,我发现还有一个开放的issue与windows容器中的内部主机dns解析相关

关于Docker 和 EF Core : No connection could be made because the target machine actively refused it,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51853190/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com