在 Debian 里 PostgreSQL 连不上 是很常见的问题,原因通常集中在 服务没启动、监听地址、认证方式、端口/防火墙 这几类。下面按最常见到最少见的顺序帮你排查。
systemctl status postgresql
或(老版本):
service postgresql status
如果没启动:
sudo systemctl start postgresql
sudo systemctl enable postgresql
默认 PostgreSQL 只监听 localhost:
sudo -u postgres psql -c "SHOW listen_addresses;"
查看监听端口:
ss -lntp | grep postgres
常见情况:
127.0.0.1:5432 → 只能本机连* 或具体 IP修改配置:
sudo nano /etc/postgresql/<版本>/main/postgresql.conf
listen_addresses = '*'
改完重启:
sudo systemctl restart postgresql
编辑:
sudo nano /etc/postgresql/<版本>/main/pg_hba.conf
local all all peer
如果你是 postgres 以外用户,可能要用:
local all all md5
添加:
host all all 0.0.0.0/0 md5
(生产环境请限制 IP)
改完:
sudo systemctl reload postgresql
sudo -u postgres psql -c "\du"
sudo -u postgres psql
ALTER USER youruser WITH PASSWORD 'yourpass';
telnet localhost 5432
# 或
nc -vz localhost 5432
sudo ufw allow 5432
云服务器还要检查 安全组
❌ 错误:
psql -h 127.0.0.1 -U postgres
报错 peer authentication
✅ 正确:
sudo -u postgres psql
或:
psql -U youruser -h 127.0.0.1 -W
| 报错 | 原因 |
|---|---|
could not connect to server |
服务没启动 |
connection refused |
端口/地址不对 |
no pg_hba.conf entry |
没授权 |
password authentication failed |
密码错 |
peer authentication failed |
系统用户不匹配 |
systemctl status postgresqlss -lntp | grep 5432listen_addressespg_hba.conf如果你愿意,可以把 具体报错信息 或:
发出来,我可以直接帮你定位是哪一步的问题。