在linux中部署pgbouncer需完成安装、配置和服务启用三步:一、用apt/yum/dnf安装或源码编译;二、配置systemd服务文件及pgbouncer.ini(含监听、数据库映射、认证);三、重载、验证、启用并启动服务,确认active状态与端口监听。

如果您希望在Linux系统中为PostgreSQL部署Pgbouncer作为连接池服务,则需要完成安装、配置及服务启用三个核心环节。以下是具体操作步骤:
一、通过包管理器安装Pgbouncer
使用系统原生包管理工具可快速获取与发行版兼容的稳定版本,避免手动编译带来的依赖冲突问题。
1、对于基于Debian或Ubuntu的系统,执行以下命令更新软件源并安装:
2、运行 sudo apt update && sudo apt install pgbouncer。
3、对于CentOS 7或RHEL 7系统,启用EPEL仓库后安装:
4、执行 sudo yum install epel-release -y && sudo yum install pgbouncer。
5、对于CentOS 8/RHEL 8或Fedora系统,使用dnf命令:
6、运行 sudo dnf install pgbouncer。
二、手动编译安装Pgbouncer
当需要特定版本(如最新稳定版)或默认仓库中无对应包时,可通过源码编译方式安装,确保功能完整且可控性强。
1、安装编译依赖:在Ubuntu/Debian上运行 sudo apt install build-essential libevent-dev libssl-dev pkg-config。
2、在CentOS/RHEL上执行 sudo yum groupinstall "Development Tools" && sudo yum install libevent-devel openssl-devel。
3、下载Pgbouncer源码包,例如从官方GitHub发布页获取v1.20.0版本:
4、执行 wget https://github.com/pgbouncer/pgbouncer/archive/refs/tags/pgbouncer_1_20_0.tar.gz。
5、解压并进入目录:tar -xzf pgbouncer_1_20_0.tar.gz && cd pgbouncer-pgbouncer_1_20_0。
6、配置构建参数并编译安装:make && sudo make install,默认二进制路径为 /usr/local/bin/pgbouncer。
三、配置Pgbouncer服务文件
需创建或修改systemd服务单元文件,使Pgbouncer能以守护进程方式启动,并支持开机自启与日志管理。
1、编辑服务文件:sudo nano /etc/systemd/system/pgbouncer.service。
2、写入以下内容(适配手动安装路径):
3、[Unit]
4、Description=PgBouncer Connection Pooler
5、After=network.target
6、[Service]
7、Type=simple
8、User=postgres
9、Group=postgres
10、ExecStart=/usr/local/bin/pgbouncer /etc/pgbouncer/pgbouncer.ini
11、Restart=on-failure
12、[Install]
13、WantedBy=multi-user.target
四、配置Pgbouncer主配置文件
pgbouncer.ini是核心配置文件,定义监听地址、认证方式、数据库连接映射及连接池行为策略。
1、复制示例配置:sudo cp /usr/share/doc/pgbouncer/pgbouncer.ini /etc/pgbouncer/pgbouncer.ini。
2、设置监听地址与端口,在 [pgbouncer] 段中修改:
3、listen_addr = 127.0.0.1
4、listen_port = 6432
5、配置连接目标数据库,在 [databases] 段添加:
6、myapp = host=127.0.0.1 port=5432 dbname=mydb user=appuser
7、设置用户认证方式,启用 auth_type = md5 并指定 auth_file = /etc/pgbouncer/userlist.txt。
8、生成认证文件:echo '"appuser"' '"md5c1a5a1e5f9e2f5e2b5e2f5e2b5e2f5e2"' | sudo tee /etc/pgbouncer/userlist.txt(密码哈希需按实际生成)。
五、初始化并启动Pgbouncer服务
完成配置后需重载systemd配置、验证语法、启用服务并检查运行状态,确保服务处于活跃且就绪状态。
1、重载systemd配置:sudo systemctl daemon-reload。
2、检查配置文件语法是否正确:sudo pgbouncer -d -q /etc/pgbouncer/pgbouncer.ini,无输出即表示通过。
3、启用开机自启:sudo systemctl enable pgbouncer。
4、启动服务:sudo systemctl start pgbouncer。
5、确认服务状态:sudo systemctl status pgbouncer,应显示 active (running)。
6、验证监听端口:sudo ss -tlnp | grep :6432,确认pgbouncer进程已绑定指定端口。










