最稳方式是用包管理器安装,Ubuntu/Debian执行sudo apt update && sudo apt install pgbouncer,CentOS/RHEL 7先装epel-release再yum install pgbouncer,RHEL 8+/Rocky/AlmaLinux用dnf install pgbouncer;PostgreSQL 15用户建议安装pgbouncer15以避免ABI不兼容。

直接用包管理器安装最稳,别急着编译
生产环境优先走 apt 或 yum/dnf 安装,版本兼容性好、依赖自动解决、服务文件开箱即用。手动编译只在需要特定版本(比如刚发布的 pgbouncer-1.24.1)或启用了 --with-pam/--with-tls 等定制选项时才必要。
常见错误现象:systemctl start pgbouncer 报 Failed to start pgbouncer.service: Unit pgbouncer.service not found——说明包没装对,或者发行版仓库没启用(如 CentOS 7 必须先装 epel-release)。
- Ubuntu/Debian:
sudo apt update && sudo apt install pgbouncer - CentOS/RHEL 7:
sudo yum install epel-release -y && sudo yum install pgbouncer - RHEL 8+/Rocky/AlmaLinux:
sudo dnf install pgbouncer - 注意:PostgreSQL 15 用户建议装
pgbouncer15(如yum install pgbouncer15),避免 ABI 不兼容
配置文件里最关键的三块不能漏
/etc/pgbouncer/pgbouncer.ini 是核心,改错一处就起不来服务。重点不是参数多,而是这三块必须显式定义且路径/权限正确:
-
[databases]段:写成myapp = host=10.0.1.5 port=5432 dbname=mydb user=pgbouncer,别漏user;如果 PostgreSQL 启用了password_encryption = scram-sha-256,pgbouncer低于 1.22 会认证失败 -
[pgbouncer]段:auth_file必须指向真实存在的/etc/pgbouncer/userlist.txt,且文件权限为600、属主为postgres;listen_addr默认是127.0.0.1,远程访问要改成0.0.0.0并确认防火墙放行listen_port(默认6432) -
pool_mode:绝大多数业务用transaction,但如果你的应用用了set session variable或prepare statement,就得切回session模式,否则会报prepared statement "xxx" does not exist
启动前必须验证用户认证文件格式
/etc/pgbouncer/userlist.txt 看似简单,格式错一个字符就导致连接拒绝。它不是明文密码,而是 "username" "md5xxx" 的双引号包裹格式,MD5 哈希必须含用户名参与计算。
常见错误现象:客户端连上后立刻断开,pgbouncer 日志里反复出现 auth failed 或 no such user。
- 生成正确哈希的命令:
echo -n 'passwordusername' | md5sum | cut -d' ' -f1(注意-n不换行,顺序是password+username) - 文件内容示例:
"pgbouncer" "md5b9e07e8a1c2d3e4f5a6b7c8d9e0f1a2b",前后双引号、空格、末尾无换行 - 千万别用
pg_md5工具——它生成的是 PostgreSQL 内部 hash,pgbouncer不认
systemd 服务启动失败时先看这三件事
systemctl status pgbouncer 显示 failed 时,别直接重装,90% 的问题出在这三个地方:
- 检查
ExecStart路径:包管理安装的二进制通常在/usr/bin/pgbouncer,源码安装可能在/usr/local/bin/pgbouncer,systemd文件里写错路径就会not found - 确认
User和Group:必须和auth_file及pgbouncer.ini所在目录权限一致,常见设为postgres;如果用非特权用户,得确保它有读取配置和日志目录的权限 - 查
journalctl -u pgbouncer -n 50 --no-pager:最常出现的是could not open /etc/pgbouncer/pgbouncer.ini: Permission denied——因为/etc/pgbouncer目录属主不是postgres,运行sudo chown -R postgres:postgres /etc/pgbouncer即可
事务模式下应用行为不一致、连接复用失效,往往不是配置问题,而是代码里混用了长连接和短事务,这点容易被忽略。


















