与“localhost”服务器的错误连接,端口 5432 失败:连接被拒绝 服务器是否在该主机上运行并接受 TCP/IP 连接?

问题描述 投票:0回答:1

我正在尝试使用 python 构建 API(使用 FastAPI)。我已经在 Windows WSL(ubuntu) 上安装了 python 我在 Windows 上有 postgress。现在我尝试通过如下所示的 python 代码连接到 Postgresssql。但连接失败,并显示 Connection returned error

代码:

try:
        conn = psycopg2.connect(host='localhost',database='fastapi',password='xxxx',cursor_factory=RealDictCursor)
        cursor = conn.cursor()
        print("Database connection was successfull")
    except Exception as error:
        print("Connetion to database has failed")
        print("Error", error)

错误

Connetion to database has failed
Error connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused
        Is the server running on that host and accepting TCP/IP connections?

我已经浏览了 Stackoverflow 上的以下链接,但幸运的是,您能否建议可能出现的问题。

如何从 WSL 连接到 windows postgres 数据库

按照上述链接执行的步骤

为 WSL2 IP 地址添加 Windows 防火墙入站端口规则:

  1. 打开具有高级安全性的 Windows Defender 防火墙
  2. 单击新建规则...
  3. 为规则类型选择端口
  4. 选择 TCP,并为特定本地端口输入 5432
  5. 选择允许连接。从 WSL2 连接不安全,因此不要选择安全选项
  6. 至少选择公共。也可以选择域和私有。仅当选择“公共”时我才能连接
  7. 命名规则,例如Postgres - 从 WSL2 连接并创建它
  8. 右键单击新创建的规则并选择“属性”,然后单击“范围”选项卡
  9. 在远程 IP 地址下,选择这些 IP 地址,然后单击添加...并输入范围 172.0.0.1 到 172.254.254.254 10.对 IP 地址范围 192.0.0.1 至 192.254.254.254 重复步骤 9 11.单击“应用”,然后单击“确定” 12.确保规则已启用

配置 Postgres 以接受来自 WSL2 IP 地址的连接

假设默认安装/设置 Windows 版 Postgresql,以下文件位于

C:\Program Files\PostgresSQL\$VERSION\data

验证 postgresql.conf 是否有以下设置:

listen_addresses = '*'

这应该已经设置为“*”,所以这里什么也不做。

更新 pg_hba.conf 以允许来自 WSL2 范围的连接,例如对于 Postgresl 15:

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                scram-sha-256
# IPv4 local connections:
host    all             all             127.0.0.1/32       scram-sha-256
host    all             all             172.0.0.0/8        scram-sha-256
host    all             all             192.0.0.0/8        scram-sha-256

对于 Postgresql 13+,您应该使用 scram-sha-256 作为方法。

重新启动 Postgres 以使更改生效。这可以通过 Windows 服务应用程序或具有管理员权限的 cmd 来完成,例如对于 Postgresql 15:

net stop postgresql-x64-12
net start postgresql-x64-12

WSL Shell 便利

在 WSL 中,将以下内容添加到您的 ~/.bashrc 或类似内容:

# Add DNS entry for Windows host
if ! $(cat /etc/hosts | grep -q 'winhost'); then
  echo 'Adding DNS entry for Windows host in /etc/hosts'
  echo '\n# Windows host - added via ~/.bashhrc' | sudo tee -a /etc/hosts
  echo -e "$(grep nameserver /etc/resolv.conf | awk '{print $2, "   winhost"}')" | sudo tee -a /etc/hosts
fi

然后重新加载 .bashrc 更改:source ~/.bashrc

我已经安装了 psycopg2 并将其导入到代码中。

pip install psycopg2-binary

运行代码时出错

谢谢 K

python django postgresql django-rest-framework windows-subsystem-for-linux
1个回答
0
投票

终于解决了这个问题,我刚刚在 PG Server 中设置连接时将 localhost 替换为 pg admin 中的 IP 地址

© www.soinside.com 2019 - 2024. All rights reserved.