'Connect to existing instance of Postgresql from WSL 2

I'm running Ubuntu WSL 2 on Windows 10. Before I installed WSL I already had Postgresql installed on my Windows 10. I wanted to connect to the database from WSL but so far it fails.

When running:

psql

I get:

psql: error: could not connect to server: Connection refused
    Is the server running on host "127.0.0.1" and accepting
    TCP/IP connections on port 5432?

When running:

psql -h 127.0.0.1 -p 5432 -U postgres

I get:

psql: error: could not connect to server: Connection refused
    Is the server running on host "127.0.0.1" and accepting
    TCP/IP connections on port 5432?

And WSL clearly doesn't see the database. When running this:

sudo service postgresql start

It returns:

postgresql: unrecognized service

I know that one solution is to install the database in WSL but wanted to try to connect to existing instance first.



Solution 1:[1]

You should edit pg_hba.conf

  1. check wsl subnet
    execute ipconfig from cmd. Below is example.
Ethernet Adapter vEthernet (WSL)
   IPv4 Address . . . . . . . . . . . .: 172.19.230.81
  1. edit pg_hba.conf
    pg_hba.conf path is C:\Program Files\PostgreSQL\{postgresqlVersion}\data\pg_hba.conf. if you installed Windows Postgresql default install path.
    subnet mask is use value from ipconfig
host    all     all     172.19.230.0/24 md5
  1. restart postgresql you can restart postgresql from services.msc. service name is postgresql-x64-{postgresqlVersion}.

  2. access from psql

psql -h 172.19.230.81 -p 5432 -U postgres

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1