如何从 WSL2 内部连接到 Windows 主机上运行的 Postgres?

Bot*_*ázs 5 postgresql linux windows windows-subsystem-for-linux

我的 Windows 机器上运行着 Postgres,我需要从 WSL2 内部连接到它。

  • postgres windows 服务正在运行
  • 我可以使用 Windows 命令行连接到它 psql
  • WSL2 虚拟机的 IP 是172.31.210.120,网络掩码255.255.240.0(使用 确定ipfconfig)。
  • vm 内部的 windows 主机的 IP 是172.31.208.1(使用 确定cat /etc/resolv.conf
  • 我可以使用curl http://172.31.208.1:8080. 如果我记录传入请求的 IP,我会得到172.31.210.120这验证两个 IP 是否正确。
  • 我将以下行添加到pg_hba.confhost all all 172.31.210.120/20 scram-sha-256
  • 我重新启动了 postgres windows 服务

如果我尝试使用以下命令从 WSL 连接到它:

$ psql --host=172.31.208.1 --port=5432 --user=postgres
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

psql: error: could not connect to server: could not connect to server: Connection timed out
        Is the server running on host "172.31.208.1" and accepting
        TCP/IP connections on port 5432?
Run Code Online (Sandbox Code Playgroud)

注意:我也尝试使用测试连接,telnet但它也失败了。

下面的日志c:\Program Files\PostgreSQL\13\data\log\没有显示任何错误或任何连接尝试的迹象。

我在这里缺少什么?

Bot*_*ázs 5

如果有人遇到同样的问题,我是这样解决的:

我需要添加 Windows 防火墙规则:

  • 打开“高级安全Windows Defender防火墙”(可以通过在开始菜单中搜索找到)
  • 单击“新规则...”
  • 创建新的 TCP/IP 规则
    • 协议:TCP
    • 端口:5432
    • 允许连接
  • 添加后,单击新创建的规则并从侧栏中选择“属性...”
  • 在“范围”选项卡上,指定 WSL2 虚拟机的 IP 地址(例如 172.31.208.0/24)

如果您执行了我原来问题中的所有其他操作(获取两个 IP,将 VM IP 添加到pg_hba.conf),那么从 WSL2 命令行连接到主机 IP 就可以了。