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

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.