将远程MySQL数据库连接到Heroku Rails应用

时间:2018-11-03 12:26:07

标签: mysql ruby-on-rails api heroku

我刚刚制作了一个可以在localhost上运行的api,但是将其部署到Heroku并通过邮递员(https://app_name.herokuapp.com/api/v1/ads)发送GET请求后,出现了500个内部服务器错误。当我签出heroku logs时,我得到了:

2018-11-03T09:21:21.115723+00:00 heroku[router]: at=info method=GET path="/api/v1/ads/1" host=app_name.herokuapp.com request_id=ea2d91ec-876f-4734-bf3b-997cdd9a5cca fwd="79.150.223.197" dyno=web.1 connect=0ms service=26ms status=500 bytes=274 protocol=https

在生产环境下,在我的database.yml内部,我的api链接到这样的外部数据库:

production:
  <<: *default
  host: host_name
  database: db_name
  adapter: mysql2
  encoding: utf8
  username: user_name
  password: ENV['DB_PASSWORD']

从此来源:Remote mysql database on Heroku app

heroku config:add DATABASE_URL=mysql://username:password@host:3306/dbname

又回来了:

Setting DATABASE_URL and restarting ⬢ app_name... !
 ▸    Cannot overwrite attachment values DATABASE_URL.

然后基于的问题:How to change DATABASE_URL for a heroku application

在Heroku中添加了一个ClearDB mysql插件,并删除了Postgres插件。

然后我这样做了:

heroku config:add CLEARDB_DATABASE_URL=mysql://username:password@host:3306/dbname

然后把它取回来:

Setting CLEARDB_DATABASE_URL and restarting ⬢ app_name... done, v16
CLEARDB_DATABASE_URL: mysql://username:password@host:3306/dbname

然后尝试发送新的GET请求到https://app_name.herokuapp.com/api/v1/ads并取回:

<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta charset="utf-8">
        <title>Application Error</title>
        <style media="screen">
          html,body,iframe {
            margin: 0;
            padding: 0;
          }
          html,body {
            height: 100%;
            overflow: hidden;
          }
          iframe {
            width: 100%;
            height: 100%;
            border: 0;
          }
        </style>
    </head>
    <body>
        <iframe src="//www.herokucdn.com/error-pages/application-error.html"></iframe>
    </body>
</html>

heroku日志给出了这一点:

2018-11-03T11:53:13.315968+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/api/v1/ads/1" host=app_name.herokuapp.com request_id=0f339471-a5b8-4402-9941-d3aad757f9c7 fwd="79.150.223.197" dyno= connect= service= status=503 bytes= protocol=https

我几乎尝试了一切。有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

确保已设置所有环境变量

在您的Heroku App环境中,设置以下内容:

CLEARDB_DATABASE_URL = mysql://username:password@host:3306
DB_PASSWORD = <YOUR PASSWORD>
DB_NAME = db_name

在database.yml

production:
  <<:       *default
  host:     ENV['CLEARDB_DATABASE_URL']
  database: ENV['DB_NAME']
  adapter:  mysql2
  encoding: utf8
  username: user_name
  password: ENV['DB_PASSWORD']

请确认默认PORT与生产数据库相同。如果不: 设置端口

production:
  <<:   *default
  port: 3306
  ...