Debian 上部署 PostgreSQL 的网络配置要点
一 核心配置清单
- 监听与端口:在 postgresql.conf 中设置 listen_addresses = ‘*’(或指定内网接口),确认 port = 5432;默认仅本地监听,需显式放开远程监听。
- 客户端认证:在 pg_hba.conf 中为需要的来源网段添加规则,例如:
- 仅内网:host all all 192.168.1.0/24 scram-sha-256
- 任意来源(不推荐生产):host all all 0.0.0.0/0 scram-sha-256
建议使用 scram-sha-256 而非 md5。
- 防火墙放行:在 UFW 中执行 sudo ufw allow 5432/tcp;如使用 iptables,放行 TCP 5432 并持久化规则。
- 服务重启:修改后执行 sudo systemctl restart postgresql(或带版本的服务单元)。
- 路径提示:Debian 常见实例配置目录为 /etc/postgresql/{version}/main/(如 /etc/postgresql/15/main/)。
二 文件与参数示例
- postgresql.conf(关键项)
- listen_addresses = ‘*’
- port = 5432
- pg_hba.conf(示例规则,按最小权限原则收紧)
-
本地 Unix 域套接字
local all all peer
-
本地环回
host all all 127.0.0.1/32 scram-sha-256
-
内网网段
host all all 192.168.1.0/24 scram-sha-256
-
如需临时开放公网(务必限制来源并尽快收敛)
host all all 0.0.0.0/0 scram-sha-256
- 说明:Debian 默认仅本地访问,必须同时调整 postgresql.conf 与 pg_hba.conf 才能远程连接。
三 连通性验证与排障
- 本机监听与端口:ss -lntp | grep 5432 或 netstat -tlnp | grep 5432,应看到 0.0.0.0:5432 或指定接口的监听。
- 端口连通性:从客户端测试 nc -zv 服务器IP 5432 或 telnet 服务器IP 5432。
- 应用连接:psql -h 服务器IP -p 5432 -U 用户名 -d 数据库。
- 日志排查:/var/log/postgresql/postgresql-{version}-main.log 可快速定位认证失败、监听地址不匹配等问题。
四 安全与最佳实践
- 最小暴露面:优先仅放行受控网段(如 192.168.1.0/24),避免使用 0.0.0.0/0;云环境配合 安全组/NACL 做白名单。
- 强认证与口令策略:使用 scram-sha-256,为 postgres 及业务角色设置强密码并定期轮换。
- 加密传输:在 postgresql.conf 启用 ssl = on,配置服务器证书与私钥,强制或优先使用 SSL/TLS 连接。
- 主机解析:确保客户端可解析数据库主机名(配置 DNS 或 /etc/hosts),避免因解析失败导致连接异常。
- 变更管控:变更前备份 postgresql.conf 与 pg_hba.conf,变更后按序重载并观察日志与监控。