0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rails +MySQLのプロジェクトをherokuへデプロイ

Last updated at Posted at 2019-11-26

RailsのデフォルトDBはSQLiteですが、
MySQLにしたものとして先に進めます
MySQL導入方法
https://qiita.com/shigeshige/items/02ce019e02bcfff14b9b
今回はheorkuへ会員登録したものとして先に進めます

production環境

実際にHerokuでデプロイした後もMySQLで動くようにします

デフォルトでfalseとなっている以下の箇所をtrueに変更

Railsは本番環境での動的な画像の表示がデフォルトでオフになっています。

config/environments/production.rb
# 以下の箇所を変更
config.assets.compile = true
config.assets.initialize_on_precompile=false

heroku だと、 sqlite3 がビルドできないので、開発環境でだけ使うよ、っていう宣言が必要
 (heroku では、 production の gem だけビルドされる)

↓を削除し

Gemfile

gem 'sqlite3'

代わりに↓を挿入する

Gemfile

gem 'sqlite3', group: [:development, :test]
gem 'mysql2'

※ Rails 5以降の場合はrails_12factorは不要のようです
参考記事(ありがとうございます)
https://qiita.com/jnchito/items/54eb7b3df322fc86675e

$ bundle install
コミットしておきます

Heroku作成

$ heroku create
$ git push heroku master

cleardbアドオンを追加

後述するアドオンの追加のところで、Herokuにクレジットカード情報を登録しておく必要がある(お金はかかりません)ので、登録しておいてください。

$ heroku addons:create cleardb:ignite

heroku-postgresqlアドオンを削除

$ heroku addons:destroy heroku-postgresql -a <アプリ名>

DATABASE_URLを編集

$ heroku config | grep CLEARDB_DATABASE_URL
CLEARDB_DATABASE_URL:mysql2://<ユーザー名>:<パスワード>@<ホスト名>/<データベース名>?reconnect=true

環境変数を設定

それぞれを設定する

DATABASE_URLをmysql2に書き換えてください

heroku config:add DATABASE_URL='mysql2://<ユーザー名>:<パスワード>@<ホスト名>/<データベース名>?reconnect=true'
heroku config:add DB_USERNAME='<ユーザー名>'
heroku config:add DB_PASSWORD='<パスワード>'
heroku config:add DB_HOSTNAME='<ホスト名>'
heroku config:add DB_NAME='<データベース名>'
heroku config:add DB_PORT='3306'
heroku config
で確認できます

database.ymlに設定

database.yml
production:
  <<: *default
  database: <%= ENV['DB_NAME'] %> 
  username: <%= ENV['DB_USERNAME'] %>
  password: <%= ENV['DB_PASSWORD'] %>

Herokuにデプロイ

$ git push heroku master

$ heroku run rake db:create
$ heroku run rake db:migrate

テストデータがある場合
$ heroku run rake db:seed
$ heroku open

でデプロイできました!!!
色々とうまくいかない場合もありましたがなんとかできました
参考になれば幸いです

0
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?