G.S*_*G.S 5 postgresql windows-subsystem-for-linux
我在Windows计算机上运行Postgres 11服务。如何从wsl连接到此数据库?
尝试:su-Postgres
postgres@LAPTOP-NQ52TKOG:~$ psql
psql: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"
Run Code Online (Sandbox Code Playgroud)
尝试连接WSL Postgres,但我不想使用以下命令运行Ubuntu Postgres:
sudo /etc/init.d/postgresql start
小智 16
在 WSL2 中,您需要使用主机 IP 进行连接
获取主机IP
grep nameserver /etc/resolv.conf | awk '{print $2}'
那么您需要在“具有高级安全性的 Windows Defender 防火墙”中允许 TCP 5432 入站规则
我自己做了 PS.you 仍然需要在防火墙中允许 TCP 5432
把它放在 ~/.bashrc
cat /etc/hosts | grep 172.; test $? -eq 0 && $1 || echo -e "$(grep nameserver /etc/resolv.conf | awk '{print $2, " host"}')\n$(cat /etc/hosts)" | sudo tee /etc/hosts
如果之前不存在,则将主机 IP 附加到 /etc/hosts(通常在重新启动 wsl 或计算机时发生)
然后
psql -h host -p 5432 -U postgres
Run Code Online (Sandbox Code Playgroud)
小智 7
明确指定您的主机、端口和用户名 例如:
psql -h 127.0.0.1 -p 5432 -U postgres
Run Code Online (Sandbox Code Playgroud)
WSL2 动态分配 IP 地址,甚至无需重新启动 Windows 即可更改 IP 地址。因此,要可靠地连接,我们需要:
psql. 我们将通过.bashrc和使这变得方便alias。不幸的是,我找不到 WSL2 IP 地址范围的确切规范。从几次测试/重启来看,WSL2 似乎正在分配范围内的 IP 地址,172.*.*.*因此我们将在配置防火墙和 Postgres 时使用它。
为 WSL2 IP 地址添加 Windows 防火墙入站端口规则:
Windows Defender Firewall with Advanced SecurityNew Rule...Port规则类型TCP并Specific local ports输入5432Allow the connection。从 WSL2 连接将不安全,所以不要选择安全选项Public。可以选择Domain和Private。如果Public被选中,我只能连接Postgres - connect from WSL2并创建它Properties然后单击Scope选项卡Remote IP address选择These IP addresses然后点击Add...并输入范围172.0.0.1,以172.254.254.254和应用更改配置 Postgres 以接受来自 WSL2 IP 地址的连接
假设 Postgresql for Windows 的默认安装/设置以下文件位于 C:\Program Files\PostgresSQL\$VERSION\data
验证是否postgresql.conf具有以下设置:
listen_addresses = '*'
Run Code Online (Sandbox Code Playgroud)
这应该已经设置为'*'所以这里什么都不做。
更新pg_hba.conf以允许来自 WSL2 范围的连接,例如:
# TYPE DATABASE USER ADDRESS METHOD
# IPv4 local connections:
host all all 127.0.0.1/32 md5
host all all 172.0.0.0/8 md5
Run Code Online (Sandbox Code Playgroud)
重新启动 Postgres 以使更改生效。这可以通过 WindowsServices应用程序或cmd使用管理员权限完成,例如 Postgresql 12:
net stop postgresql-x64-12
net start postgresql-x64-12
Run Code Online (Sandbox Code Playgroud)
WSL 壳牌便利
在 WSL 中,将以下内容添加到您的~/.bashrc或类似内容中:
listen_addresses = '*'
Run Code Online (Sandbox Code Playgroud)
然后重新加载您的.bashrc更改:source ~/.bashrc
用法
# TYPE DATABASE USER ADDRESS METHOD
# IPv4 local connections:
host all all 127.0.0.1/32 md5
host all all 172.0.0.0/8 md5
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
326 次 |
| 最近记录: |