如何从本地系统连接到Linode中的postgres

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

我有一个 python 脚本来将数据添加到 postgres 数据库。在测试过程中,我在本地系统中创建了一个数据库并且它运行良好。现在我的数据库在 linode 中运行。我不确定如何从本地系统连接到数据库。我将数据库详细信息存储在 python 文件中,如下所示

DATABASE = 'my_database'
HOST = <IP_ADDRESS> # the ip_address of the linode instance
PORT = '5432'
USER = 'database_user'
PASSWORD = 'database_password'

我使用上面的代码来访问数据库。如果数据库在本地主机中运行,则主机等于

HOST = 'localhost'

当我从本地系统运行 python 脚本以连接到数据库时,这是我收到的消息

psycopg2.OperationalError: connection to server at "<IP_ADDESS>", port 5432 failed: Connection refused
    Is the server running on that host and accepting TCP/IP connections?

我不知道如何连接到linode中运行的数据库。

python postgresql linode
2个回答
0
投票

我通过编辑

pg_hba.conf
解决了这个问题。

  1. 在 linode 实例中,导航至

    /var/lib/pgsql/data

  2. 在目录中,打开

    pg_hba.conf
    并在IPv4本地连接下添加以下行

host    all             all             <local system's Public IP ADDRESS>/32   md5
  1. 保存文件并重新启动 postgres。
  2. 启动到 linode 实例的 SSH 隧道
  3. 将数据库详细信息中的主机和端口更改为
    127.0.0.1
    以及隧道期间选择的端口。就我而言,是
    5433
  4. 现在运行 python 脚本应该能够使本地系统与 linode 实例中运行的 postgres 服务器连接。

0
投票

官方指南(对于 Windows,请查看此处) 远程访问 Postgresql 建议使用 SSH 隧道

ssh -f -L 5433:127.0.0.1:5432 username@remote-host -N
© www.soinside.com 2019 - 2024. All rights reserved.