You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法远程连接PgBouncer求助(Vultr Ubuntu 20.04环境)

PgBouncer仅允许本地连接,公网IP连接被拒的排查与解决

问题描述

我在Vultr的Ubuntu 20.04服务器上安装了PostgreSQL及PgBouncer连接池工具,完成配置后,PgBouncer仅允许本地(127.0.0.1)连接,使用服务器公网IP连接时被拒绝。已在防火墙开放6432和5432端口,执行命令sudo psql -h 139.**.22*.** -U myuser -d mydb -p 6432时,持续报错:

psql: error: could not connect to server: Connection refused. Is the server running on host "139..22*." and accepting TCP/IP connections on port 6432?

已配置的相关文件信息

postgresql.conf

listen_addresses = '*'
port = 5432

pgbouncer.ini

[databases]
postgres = host=127.0.0.1 port=5432 dbname=postgres
mydb = host=127.0.0.1 port=5432 dbname=mydb

[pgbouncer]
listen_addr = *
listen_port = 6432

pg_hba.conf

# IPv4 local connections:
host    all             all             0.0.0.0/0            md5

# IPv6 local connections:
host    all             all             ::1/128                 md5

排查与解决步骤

  • 验证PgBouncer实际监听地址
    执行命令查看PgBouncer的监听状态:

    sudo netstat -tulpn | grep pgbouncer
    

    如果输出显示监听地址是127.0.0.1:6432而非0.0.0.0:6432,说明配置未生效,重启PgBouncer服务:

    sudo systemctl restart pgbouncer
    

    若重启后问题依旧,检查配置文件语法:

    pgbouncer -d -v /etc/pgbouncer/pgbouncer.ini
    

    根据输出的错误提示修正配置后,再次重启服务。

  • 检查Vultr控制面板防火墙
    除了服务器本地的ufw/iptables规则,登录Vultr后台检查防火墙组是否添加了6432端口的入站规则,且规则已应用到目标服务器。

  • 本地测试连通性
    在服务器本地执行以下命令:

    psql -h 0.0.0.0 -U myuser -d mydb -p 6432
    

    如果本地能连接,说明问题出在公网路由或Vultr防火墙;如果本地也无法连接,先检查PgBouncer服务状态:

    sudo systemctl status pgbouncer
    

    若服务未启动,执行启动命令:

    sudo systemctl start pgbouncer
    
  • 配置PgBouncer认证规则
    默认未配置认证时,PgBouncer可能拒绝外部连接。在pgbouncer.ini的[pgbouncer]段添加或修改:

    auth_type = md5
    auth_file = /etc/pgbouncer/userlist.txt
    

    然后创建认证文件并添加用户:

    echo '"myuser" "mypassword"' | sudo tee /etc/pgbouncer/userlist.txt
    sudo chmod 600 /etc/pgbouncer/userlist.txt
    sudo chown postgres:postgres /etc/pgbouncer/userlist.txt
    

    重启PgBouncer服务。

  • 确认PostgreSQL配置生效
    虽然pg_hba.conf已配置允许所有IP连接,但需重启PostgreSQL使配置生效:

    sudo systemctl restart postgresql
    

内容的提问来源于stack exchange,提问作者Johndev247

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 04:28:24