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

启动Telegram Bot(aiogram)连接PostgreSQL时遇连接拒绝错误

解决psycopg2.OperationalError:本地PostgreSQL连接被拒绝问题

遇到的错误信息:

connection to server at "127.0.0.1", port 5432 failed: Connection refused (0x0000274D/10061)
        Is the server running on that host and accepting TCP/IP connections?

你猜测Bot和数据库用同一本地IP导致问题,这个说法不成立——本地服务之间本来就通过127.0.0.1/localhost通信,问题出在以下几个常见环节,按顺序排查:

  • 检查PostgreSQL服务是否启动

    • Windows:打开「服务」(运行services.msc),找到PostgreSQL相关服务,确认状态为「正在运行」,未启动则右键启动。
    • Linux/macOS:执行sudo systemctl status postgresql查看状态,未运行则用sudo systemctl start postgresql启动。
  • 确认PostgreSQL监听TCP/IP连接

    • 找到PostgreSQL的postgresql.conf配置文件(路径根据系统版本不同:Windows一般在C:\Program Files\PostgreSQL\<版本>\data,Linux在/var/lib/postgresql/<版本>/main,macOS在/Library/PostgreSQL/<版本>/data)。
    • 查找listen_addresses参数,确保值为'*'或包含'127.0.0.1'(默认'localhost'也支持本地连接)。修改后重启PostgreSQL服务。
  • 配置pg_hba.conf允许本地TCP连接

    • 同样在data目录下找到pg_hba.conf,添加或确认存在以下规则:
      host    all             all             127.0.0.1/32            scram-sha-256
      
      认证方式可根据你的PostgreSQL版本调整(比如旧版本用md5),修改后重启服务。
  • 核对Bot连接参数

    • 检查aiogram代码中的数据库连接配置,确保host是'127.0.0.1'或'localhost',端口为5432,用户名、密码、目标数据库名均无拼写错误。
  • 排查防火墙/安全软件拦截

    • Windows:检查Windows防火墙是否允许PostgreSQL通过5432端口通信,可临时关闭防火墙测试。
    • Linux:执行sudo ufw allow 5432开放端口,或检查iptables规则。
    • 第三方杀毒、安全软件也可能拦截,暂时关闭验证是否解决问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 06:50:03