如何在heroku中连接我的postgres数据库?

时间:2017-06-01 13:41:35

标签: ruby postgresql heroku rack

我正在学习机架,我构建了一个测试todo应用程序。我的测试应用程序使用postgres db。我正在尝试将我的应用部署到heroku免费帐户。

Currenlty我正在尝试使用此

连接到postgres
DB = PG.connect :hostaddr => "localhost", :port => 5432, :dbname => 'testdb', :user => "postgres", :password => "postgres"

我检查了我的日志,因为当我访问网址并发现

时,我的应用程序无法正常工作
2017-06-01T13:22:35.540907+00:00 app[web.1]: Puma starting in single mode...
2017-06-01T13:22:35.540929+00:00 app[web.1]: * Version 3.8.2 (ruby 2.3.4-p301), codename: Sassy Salamander
2017-06-01T13:22:35.540930+00:00 app[web.1]: * Min threads: 5, max threads: 5
2017-06-01T13:22:35.540975+00:00 app[web.1]: * Environment: production
2017-06-01T13:22:35.583653+00:00 app[web.1]: ! Unable to load application: PG::ConnectionBad: could not connect to server: Connection refused
2017-06-01T13:22:35.583655+00:00 app[web.1]:    Is the server running on host "127.0.0.1" and accepting
2017-06-01T13:22:35.583656+00:00 app[web.1]:    TCP/IP connections on port 5432?
2017-06-01T13:22:35.583775+00:00 app[web.1]: bundler: failed to load command: puma (/app/vendor/bundle/ruby/2.3.0/bin/puma)
2017-06-01T13:22:35.583838+00:00 app[web.1]: PG::ConnectionBad: could not connect to server: Connection refused
2017-06-01T13:22:35.583839+00:00 app[web.1]:    Is the server running on host "127.0.0.1" and accepting
2017-06-01T13:22:35.583840+00:00 app[web.1]:    TCP/IP connections on port 5432?

编辑1

我在heroku中找到了postgres db creds并使用了它并得到了这个错误

2017-06-01T14:27:11.889525+00:00 app[web.1]: Puma starting in single mode...
2017-06-01T14:27:11.889599+00:00 app[web.1]: * Version 3.8.2 (ruby 2.3.4-p301), codename: Sassy Salamander
2017-06-01T14:27:11.889633+00:00 app[web.1]: * Min threads: 5, max threads: 5
2017-06-01T14:27:11.889671+00:00 app[web.1]: * Environment: production
2017-06-01T14:27:11.934347+00:00 app[web.1]: ! Unable to load application: PG::ConnectionBad: could not translate host name "ec2-23-23-234-118.compute-1.amazonaws.com" to address: Name or service not known
2017-06-01T14:27:11.934473+00:00 app[web.1]: bundler: failed to load command: puma (/app/vendor/bundle/ruby/2.3.0/bin/puma)
2017-06-01T14:27:11.934522+00:00 app[web.1]: PG::ConnectionBad: could not translate host name "ec2-23-23-234-118.compute-1.amazonaws.com" to address: Name or service not known

2 个答案:

答案 0 :(得分:1)

您可以从DATABASE_URL环境变量

获取Heroku上的数据库配置
ENV['DATABASE_URL']

这是一个连接网址,如下所示:

postgres://$user:$pass@$db_host.com:5432/$db_name

您可以将该字符串直接传递给PG客户端初始化程序:

DB = PG.connect ENV['DATABASE_URL']

DB现在是您的连接数据库客户端。

答案 1 :(得分:0)

使用此解决了它DB = PG.connect ENV["HEROKU_POSTGRESQL_SILVER_URL"]