从 WSL 2 连接到 Postgresql 的现有实例

Pio*_*ski 7 postgresql windows-subsystem-for-linux wsl-2

我在 Windows 10 上运行 Ubuntu WSL 2。在安装 WSL 之前,我已经在 Windows 10 上安装了 Postgresql。我想从 WSL 连接到数据库,但到目前为止它失败了。

运行时:

psql
Run Code Online (Sandbox Code Playgroud)

我得到:

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?
Run Code Online (Sandbox Code Playgroud)

运行时:

psql -h 127.0.0.1 -p 5432 -U postgres
Run Code Online (Sandbox Code Playgroud)

我得到:

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?
Run Code Online (Sandbox Code Playgroud)

而且 WSL 显然看不到数据库。运行此命令时:

sudo service postgresql start
Run Code Online (Sandbox Code Playgroud)

它返回:

postgresql: unrecognized service
Run Code Online (Sandbox Code Playgroud)

我知道一种解决方案是在 WSL 中安装数据库,但想首先尝试连接到现有实例。

S.H*_*iba 11

你应该编辑pg_hba.conf


  1. 检查从 cmd执行的wsl 子网ipconfig。下面是示例。
Ethernet Adapter vEthernet (WSL)
   IPv4 Address . . . . . . . . . . . .: 172.19.230.81
Run Code Online (Sandbox Code Playgroud)
  1. 编辑pg_hba.conf
    pg_hba.conf路径为C:\Program Files\PostgreSQL\{postgresqlVersion}\data\pg_hba.conf。如果您安装了 Windows Postgresql 默认安装路径。
    子网掩码的使用值来自ipconfig
host    all     all     172.19.230.0/24 md5
Run Code Online (Sandbox Code Playgroud)
  1. 重新启动 postgresql 您可以从 重新启动 postgresql services.msc。服务名称是postgresql-x64-{postgresqlVersion}.

  2. 从 psql 访问

psql -h 172.19.230.81 -p 5432 -U postgres
Run Code Online (Sandbox Code Playgroud)