Postgresql 如何从WSL连接到windows postgres数据库
我正在windows计算机上运行Postgres 11服务。 如何从wsl连接到此数据库 尝试: su-postgresPostgresql 如何从WSL连接到windows postgres数据库,postgresql,windows-subsystem-for-linux,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
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"
它试图连接WSL Postgres,我不想使用以下方式运行Ubuntu Postgres:
sudo/etc/init.d/postgresql start
明确指定主机、端口和用户名
例如:
psql-H127.0.0.1-P5432-U postgres
在WSL2中,您需要使用主机IP进行连接
获取主机IP
grep nameserver/etc/resolv.conf | awk'{print$2}'
然后,您需要在“具有高级安全性的Windows Defender防火墙”中允许TCP 5432入站规则
我做了我自己的PS。你仍然需要在防火墙中允许TCP 5432 把这个放在~/.bashrc中
cat/etc/hosts | grep 172。;测试$-等式0&$1 | | echo-e“$(grep nameserver/etc/resolv.conf | awk'{print$2,“host”}')\n$(cat/etc/hosts)| sudo tee/etc/hosts
如果以前不存在/etc/hosts,则将其附加主机IP(通常在重新启动wsl或计算机时发生)
然后
对我来说,有效的方法是遵循以下步骤:
- 更改pg_hba.conf以侦听所有接口:
host all 0.0.0.0/0 trust
- 开放postgresql防火墙
- 使用
中指向主机ip的主机名之一。我的主机名是:/etc/hosts
host.docker.internal
- 允许Windows和Postgres接受来自WSL2 IP地址范围的连接(默认情况下不允许)
- 在WSL2中,当通过
连接时,确定Windows/Postgresql主机的IP地址(这是动态的)。我们将通过psql
和.bashrc
来方便这一点alias
不幸的是,我找不到WSL2 IP地址范围的确切规范。从几次测试/重新启动来看,WSL2似乎正在分配范围为
- WSL2动态分配IP地址,IP地址可以更改,甚至无需重新启动Windows。因此,为了可靠连接,我们需要:
172.*.*.
的IP地址,因此我们将在配置防火墙和Postgres时使用它
为WSL2 IP地址添加Windows防火墙入站端口规则:
端口
TCP
并为特定本地端口输入5432
允许连接
。从WSL2连接将不安全,因此不要选择安全选项Public
。还可以选择域
和私有
。只有选择了Public
时,我才能连接Postgres-connectfromswsl2
,并创建它属性
,然后单击范围
选项卡远程IP地址
下,选择这些IP地址
,然后单击添加…
,然后输入范围172.0.0.1
到172.254.254
,并应用更改C:\Program files\PostgresSQL\$VERSION\data
验证postgresql.conf
是否具有以下设置:
listen_addresses = '*'
这应该已经设置为“*”
,所以这里什么都不做
更新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
重新启动Postgres以使更改生效。这可以通过Windows服务
应用程序或具有管理员权限的cmd
完成,例如Postgresql 12:
net stop postgresql-x64-12
net start postgresql-x64-12
WSL外壳的便利性
在WSL中,将以下内容添加到~/.bashrc
或类似内容中:
#为Windows主机添加DNS条目
如果$(cat/etc/hosts | grep-q‘winhost’);然后
echo“在/etc/hosts中为Windows主机添加DNS条目”
echo'\n#Windows主机-通过~/.bashrc'| sudo tee-a/etc/hosts添加
echo-e“$(grep nameserver/etc/resolv.conf | awk'{print$2,“winhost”}”)”| sudo tee-a/etc/hosts
fi
然后重新加载.bashrc
更改:source~/.bashrc
用法
psql-hwinhost-p5432-uppostgres
Postgres是否在WSL内部的Windows上运行?我得到了psql:错误:无法连接到服务器:连接被拒绝服务器是否在主机“localhost”(127.0.0.1)上运行在端口5432上接受TCP/IP连接?
同样的命令在Windows控制台中也可以正常工作……要在PosgreSQL v13上实现这一点,需要进行以下更改:1。删除listen\u addresses='*'
,因为这将阻止postgresql启动。2.在pg_hba.conf
中,我将方法设置为scram-sha-256
。还请注意,默认情况下,PosgreSQL 13侦听端口5433
。
net stop postgresql-x64-12
net start postgresql-x64-12