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

Windows10+WSL2环境下PostgreSQL、Psycopg2、Amundsen连接被拒求助

解决思路
  • 确认PostgreSQL监听地址
    PostgreSQL默认仅监听本地回环地址(127.0.0.1),若跨WSL2/Windows环境访问,需修改postgresql.conf配置:

    1. 找到配置文件路径(WSL2中通常为/etc/postgresql/15/main/postgresql.conf)
    2. 将listen_addresses的值改为'*'
    3. 重启PostgreSQL服务:sudo systemctl restart postgresql
  • 检查pg_hba.conf的访问权限规则
    修改监听地址后,需确保pg_hba.conf允许对应来源的访问:

    • 若Windows环境的Python访问WSL2内的PostgreSQL,添加规则:host all all 172.16.0.0/12 scram-sha-256(WSL2的IP段通常为172.16.0.0/12)
    • 若WSL2内部访问,确认已有规则:host all all 127.0.0.1/32 scram-sha-256
      修改后同样需重启PostgreSQL服务。
  • 区分WSL2与Windows的网络栈
    WSL2和Windows拥有独立的网络空间,localhost在两个环境中指向不同节点:

    • 若Python代码在Windows环境运行,PostgreSQL在WSL2内,需将代码中的host替换为WSL2的实际IP(在WSL2中执行ip addr show eth0查看inet字段的IP,如172.28.xxx.xxx)
    • 若Python和PostgreSQL都在WSL2内,localhost可正常使用,但需确认PostgreSQL确实监听了127.0.0.1
  • 验证端口占用与配置
    确认PostgreSQL使用的端口(默认5432)未被占用,且代码中端口配置一致:

    • 在WSL2中执行netstat -tulpn | grep postgres查看监听端口,若端口非默认,需在psycopg2.connect中添加port='xxx'参数
  • 重新适配Psycopg2环境
    确保Psycopg2与当前运行环境匹配:

    • 卸载现有版本:pip uninstall psycopg2 psycopg2-binary
    • 重新安装预编译包(避免编译依赖问题):pip install psycopg2-binary
  • 捕获详细错误信息
    修改测试代码,添加异常捕获以获取具体错误原因,帮助定位问题:

    import psycopg2
    from psycopg2 import OperationalError
    
    try:
        conn = psycopg2.connect(
            dbname='Titanic',
            user='jdwbmc',
            host='localhost',
            password='secret'
        )
        print("连接成功")
        c = conn.cursor()
        c.execute("SELECT * FROM test")
        records = c.fetchall()
        import pprint
        pprint.pprint(records)
    except OperationalError as e:
        print(f"连接错误详情: {e}")
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 17:08:18