WSL2 动态分配 IP 地址,并且 IP 地址可以更改,甚至无需重新启动 Windows。因此,为了可靠地连接,我们需要:
- 允许 Windows 和 Postgres 接受来自 WSL2 IP 地址范围的连接(默认情况下不允许)
- 从 WSL2 中,确定通过
psql 连接时的 Windows/Postgresql 主机的 IP 地址(这是动态的)。我们将通过.bashrc 和alias 为您提供便利。
很遗憾,我找不到 WSL2 IP 地址范围的确切规范。从几次测试/重启看来,WSL2 分配的 IP 地址范围为 172.*.*.*,因此我们将在配置防火墙和 Postgres 时使用它。
为 WSL2 IP 地址添加 Windows 防火墙入站端口规则:
- 打开
Windows Defender Firewall with Advanced Security
- 点击
New Rule...
- 为规则类型选择
Port
- 选择
TCP,对于Specific local ports,输入5432
- 选择
Allow 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 地址的连接
假设 Windows 的 Postgresql 默认安装/设置,以下文件位于 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 Services 应用程序或具有管理员权限的 cmd 完成,例如对于 Postgresql 12:
net stop postgresql-x64-12
net start postgresql-x64-12
WSL Shell 便利
在 WSL 中,将以下内容添加到您的 ~/.bashrc 或类似名称中:
# Add DNS entry for Windows host
if ! $(cat /etc/hosts | grep -q 'winhost'); then
echo 'Adding DNS entry for Windows host in /etc/hosts'
echo '\n# Windows host - added via ~/.bashhrc' | 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 -h winhost -p 5432 -U postgres