环境如下:
- 宿主机为Windows 11
- postgreSQL安装在宿主机上的Linux虚机中,Hypervisor是VirtualBox
- pgAdmin 4 已安装在宿主机上
本文讲述:如何通过宿主机上的pgAdmin 连接到虚拟机中的PG。
设置监听
默认的PG监听主机为localhost,外部无法连接。
postgres=# show listen_addresses;
listen_addresses
——————
localhost
(1 row)
因此第一步需要修改监听。此设置在文件$PGDATA/postgresql.conf中:
listen_addresses = '*' # what IP address(es) to listen on;
#listen_addresses = 'localhost' # what IP address(es) to listen on;
# comma-separated list of addresses;
# defaults to 'localhost'; use '*' for all
# (change requires restart)
如何修改,已经需要重启,在注释中已经说的很清楚。
重启PG:
$ pg_ctl restart
确认:
postgres=# show listen_addresses;
listen_addresses
——————
*
(1 row)
OS层面确认:
$ netstat -an|grep 5432
tcp 0 0 0.0.0.0:5432 0.0.0.0:* LISTEN
...
netstat命令的安装(若不存在):
# 查询netstat所在的包
yum whatprovides */netstat
yum install net-tools
设置端口转发
就是映射宿主机的端口5432到虚拟机中PG的监听端口5432。
可以每次在VirtualBox中改,不过建议在Vagrantfile中永久修改。在Vagrantfile中添加以下,然后重启虚机:
config.vm.network "forwarded_port", guest: 5432, host: 5432
在VirtualBox中确认:
设置HBA
修改pg_hba.conf如下,关键是最后一行:
$ cat pg_hba.conf
…
local all postgres peer
local all +athlethes,xiaoyu md5
host all postgres,lewis 0.0.0.0/0 md5
…
$ pg_ctl reload
实际上从虚机的登录信息,可以得知宿主机的地址为10.0.2.2,因此0.0.0.0/0也可以改为10.0.2.2。
Using username "vagrant".
Authenticating with public key "vagrant"
Welcome to Oracle Linux Server release 9.5 (GNU/Linux 5.15.0-206.153.7.el8uek.x8 6_64)
The Oracle Linux End-User License Agreement can be viewed here:
* /usr/share/eula/eula.en_US
For additional packages, updates, documentation and community help, see:
* https://yum.oracle.com/
Last login: Tue Jun 17 01:37:21 2025 from 10.0.2.2
pgAdmin的设置
以下是连接成功的界面: General设置:
Connection设置:
Parameters设置: 注意,如果用postgres连接,我是不知道其口令的,因此我在PG中预先修改了口令:
ALTER USER postgres WITH PASSWORD 'new_password';
评论前必须登录!
注册