解决Ubuntu上PostgreSQL连接问题可按以下步骤排查:
检查服务状态
确保PostgreSQL服务已启动:
sudo systemctl status postgresql
若未启动,使用命令启动:
sudo systemctl start postgresql
配置远程访问权限
postgresql.conf
:listen_addresses
设为'*'
以允许所有IP连接(生产环境建议指定具体IP段)。/etc/postgresql/{版本}/main/postgresql.conf
pg_hba.conf
:host all all 0.0.0.0/0 md5
(允许所有IP通过MD5密码认证)。/etc/postgresql/{版本}/main/pg_hba.conf
检查防火墙设置
若启用UFW防火墙,需允许PostgreSQL默认端口(5432):
sudo ufw allow 5432/tcp
sudo ufw reload
验证连接配置
netstat
检查端口监听:sudo netstat -plnt | grep 5432
确认输出中包含0.0.0.0:5432
(表示监听所有IP)。查看日志排查错误
若仍无法连接,查看PostgreSQL日志获取具体错误信息:
sudo tail -f /var/log/postgresql/postgresql-{版本}-main.log
安全建议:
listen_addresses = '*'
,应指定具体IP段。scram-sha-256
等强认证方式替代md5
。按以上步骤逐步排查,可解决大部分Ubuntu上PostgreSQL的连接问题。