大网数据广告活动
服务器运维问答

How can I connect to Postgres running on the Windows host from inside WSL2?

· 52CE 我爱测

I have Postgres running on my windows machine and I need to connect to it from inside WSL2. The postgres windows service is running I can connect to it from the windows command line using psql The IP of the WSL2 vm is 172.31.210.…

问题原文

原帖链接 · Botond Balázs · CC BY-SA 4.0

I have Postgres running on my windows machine and I need to connect to it from inside WSL2.

  • The postgres windows service is running
  • I can connect to it from the windows command line using psql
  • The IP of the WSL2 vm is 172.31.210.120, netmask 255.255.240.0 (determined using ipfconfig).
  • The IP of the windows host from inside the vm is 172.31.208.1 (determined using cat /etc/resolv.conf)
  • I can connect to a simple web server running on the host from the vm with curl http://172.31.208.1:8080. If I log the IP of the incoming requests, I get 172.31.210.120 so this verifies that both IPs are correct.
  • I added the following line to pg_hba.conf: host all all 172.31.210.120/20 scram-sha-256
  • I restarted the postgres windows service

If I try to connect to it from WSL using the following command:

$ psql --host=172.31.208.1 --port=5432 --user=postgres

I get this error:

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?

NOTE: I also tried to test the connection using telnet but it failed too.

The logs under c:\Program Files\PostgreSQL\13\data\log\ show no errors or any signs that there was a connection attempt.

What am I missing here?

已采纳解答

原帖链接 · Botond Balázs · CC BY-SA 4.0

Here is how I solved this in case somebody has the same problem:

I needed to add a Windows Firewall rule:

  • Open "Windows Defender Firewall with Advanced Security" (you can find it by searching in the Start Menu)
  • Click "New rule..."
  • Create a new TCP/IP rule
    • Protocol: TCP
    • Ports: 5432
    • Allow Connection
  • After adding it, click on the newly created rule and choose "Properties..." from the sidebar
  • On the Scope tab, specify the IP address of your WSL2 virtual machine (E.g. 172.31.208.0/24)

If you do everything else in my original question (get both IPs, add VM IP to pg_hba.conf), then connecting to the host IP from the WSL2 command line will work.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2020-11-10)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。