从 WSL 上的 django 运行 连接到 Windows 上的 Postgres 运行

Connecting to Postgres running on Windows from django running on WSL

我主要在 windows 上开发,但我正在使用 WSL 测试我的应用程序,因为我会将它推送到 linux 服务器。我当前的问题是将 Django 应用程序,WSL 上的 运行 连接到 postgres,windows 上的 运行。许多文章解释了如何在 WSL 上连接到 postgres 运行,但反过来却没有。

我无法测试所有这些,因此我们可能需要调整此答案中的一些项目,但这是我推荐的步骤:

  • 首先,假设这是一个 WSL2 实例,mDNS 应该可以从 WSL 访问 Windows 主机 IP。对于初学者,请从 WSL 内部尝试 ping $(hostname).local

  • 如果这可以解析 IP 地址,那么这是第 1 步。如果不能,则还有其他选择(参见 this answer)。

  • 我假设 ping 不会 return 由于防火墙。您需要一个规则来启用它。来自管理员 PowerShell,New-NetFirewallRule -DisplayName "WSL Ping" -Direction Inbound -InterfaceAlias "vEthernet (WSL)" -Action Allow -Protocol ICMPv4。然后再次尝试 ping $(hostname).local。删除 Remove-NetFirewallRule -DisplayName "WSL Ping"

    的规则
  • 如果可行,那么您就真正找到了如何访问 PostgreSQL 的答案——在该接口上设置防火墙规则。它应该类似于 New-NetFirewallRule -DisplayName "WSL PostgreSQL" -Direction Inbound -InterfaceAlias "vEthernet (WSL)" -Action Allow -Protocol TCP -LocalPort 5432.

  • 然后您应该能够使用 {computername}.local 地址从 WSL 中的 Django 应用访问它。