Ubuntu 上 PostgreSQL 连接失败的定位与修复
一、先快速定位问题
sudo systemctl status postgresql(或 sudo service postgresql status)。若未运行,先启动:sudo systemctl start postgresql。sudo -u postgres psql -h 127.0.0.1 -p 5432 与 psql -U postgres(本地 Unix 域套接字)。nc -vz <服务器IP> 5432 或 telnet <服务器IP> 5432。sudo tail -n 50 /var/log/postgresql/postgresql-<版本>-main.log。ss -lntp | grep 5432 或 netstat -a | grep PGSQL。二、常见错误与对应修复
could not connect to server: No such file or directory ... /var/run/postgresql/.s.PGSQL.5432。/var/run/postgresql/ 或 /tmp/);3) 必要时重启服务以重建套接字:sudo systemctl restart postgresql;4) 若套接字在不同目录,可在 postgresql.conf 的 unix_socket_directories 中统一目录,或创建软链(不建议长期使用):ln -s /tmp/.s.PGSQL.5432 /var/run/postgresql/.s.PGSQL.5432。peer/ident 认证不匹配当前系统用户。pg_hba.conf,将对应行改为 trust 或 md5,然后 sudo systemctl reload postgresql;或切换到与数据库用户同名的系统用户再连接。postgresql.conf 设置 listen_addresses = '*';pg_hba.conf 增加规则(示例):host all all 0.0.0.0/0 md5(生产建议改为具体网段并使用更安全的认证方式);sudo systemctl restart postgresql;sudo ufw allow 5432/tcp 或 sudo iptables -I INPUT -p tcp --dport 5432 -j ACCEPT。sudo chown postgres:postgres /etc/ssl/private/ssl-cert-snakeoil.keysudo chmod 640 /etc/ssl/private/ssl-cert-snakeoil.key三、配置文件与路径速查
/etc/postgresql/<版本>/main/postgresql.conf 与 pg_hba.conf。listen_addresses = '*'(或指定内网 IP)pg_hba.conf 示例:
local all all peer(或 md5/trust 视场景)host all all 127.0.0.1/32 md5host all all 192.168.1.0/24 md5sudo systemctl reload postgresql(或 restart 使监听地址变更立即生效)。/var/log/postgresql/postgresql-<版本>-main.log,优先从这里看具体报错行号与原因。四、远程连接与安全建议
0.0.0.0/0),并使用强认证(如 scram-sha-256 或 md5);