gpt4 book ai didi

ruby - 如何在 ruby​​ 中使用 ssh 隧道连接 postgres 数据库

转载 作者:数据小太阳 更新时间:2023-10-29 08:02:59 29 4
gpt4 key购买 nike

这是我的问题,我想通过 ruby​​ 脚本访问我们的数据库,我可以使用 ssh 隧道通过 PSequal 连接到数据库。当我尝试从 ruby​​ 连接到数据库时,它总是返回超时错误。

错误信息是这样的:“无法连接到服务器:操作超时 服务器是否在主机“HOSTNAME”(IP 地址)上运行并接受 端口 5432 上的 TCP/IP 连接"

我曾尝试在终端中使用“psql -h -d -U”登录,但我得到了相同的答案。谢谢

def connectDb
begin
file = File.open("pem file")
gateway = Net::SSH::Gateway.new('hostname', 'username', keys_only: true, port: 22, key_data: file)
port_pg = gateway.open('hostname', 5432)
puts port_pg
con = PG::Connection.open('hostname', portpg, "", "", 'dbname', 'username', 'password')
rescue PG::Error => e
puts e.message
end
end

最佳答案

确保您的 Postgres 服务器正在监听正确的端口在 postgresql.conf 中(可能位于 /etc/postgresql/9.3/main/postgresql.conf 注释掉

#listen_addresses = 'localhost'

并在所有端口上添加监听

listen_addresses = '*'

Postgres 配置文件可能归 Postgres 所有,这会使它们更难找到。

登录到您的 postgres 数据库并运行

SHOW config_file;

这应该会为您提供位置,以便您能够编辑文件

看看this StackOverflow 线程以获取有关此的更多信息编辑文件后(您可能需要 sudo 权限才能执行此操作,即 sudo vim path_to/config_file )您需要重新启动 postgres 以使更改生效。您如何重新启动将取决于 pg 的设置方式,但很可能它作为服务运行,因此下面的内容应该可以解决问题。

sudo service postgres restart

如果没有那么问你的主机如何重启

在您的 database.yml 文件中为远程服务器创建一个条目例如

remote:
adapter: postgresql
database: remote_db_name
username: xxx
password: xxx
pool: 5
timeout: 5000
host: ip_address_for_remote_server
port: prob_3306_but_whatever_port_you_have_configured_on_remote_server
strict: false

然后创建一组特定的模型来处理远程数据库并与database.yml条目建立连接

例如

class SomeTableNameOnRemoteServer < ActiveRecord::Base
establish_connection :remote
#etc...

不要试图使用已经连接到本地数据库的模型。如果您想共享逻辑,则创建一个模块并将该模块包含在两个模型类中

进一步阅读可能会有所帮助。这是关于如何在 DigitalOcean 液滴上设置和配置 pg 的指南

https://www.digitalocean.com/community/tutorials/scaling-ruby-on-rails-setting-up-a-dedicated-postgresql-server-part-3

页面下方有一个关于远程访问的部分,但您可能会发现整个文档都很有用,因此不要在此处粘贴内容。

关于ruby - 如何在 ruby​​ 中使用 ssh 隧道连接 postgres 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37950282/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com