LoginSignup
1
0

More than 1 year has passed since last update.

Docker+RailsAPIモード+MySQL設定プロジェクトをHerokuにデプロイ

Last updated at Posted at 2021-08-07

※自分用メモ

開発環境はDockerでフォルダをバックエンド(RailsAPI)、フロントエンド(Vue)に分けHerokuにデプロイするまでの流れです。
この記事ではバックエンドフォルダをHerokuにデプロイするまでの行程を紹介します。

Dockerで開発したRailsプロジェクト(APIモードじゃない)をHeorkuにデプロイするやり方は前に書いた記事で紹介したんですが、上手くいかなかったので、APIモードのRailsプロジェクトでは今回の方法を採用しました。
前回記事
https://qiita.com/ryota-0906/items/55c6204532988aa73c82

1 前提条件

1 クレジットカード登録済みのherokuアカウント
2 heroku cliインストール済み

2 コンテナ停止&server.pidを削除

$ cd <RailsAPIディレクトリ>
$ docker-compose stop
$ rm -f tmp/pids/server.pid

3 heroku準備 

$ heroku login --interactive
$ heroku container:login 
$ heroku create アプリ名
Creating ⬢ アプリ名... done
https://アプリ名.herokuapp.com/ | https://git.heroku.com/アプリ名.git

4 herokuでMySQLを使えるようにする。 

HerokuでMySQLを使うためにClearDBのアドオンを追加

$ heroku addons:create cleardb:ignite --app アプリ名
$ Creating cleardb:ignite on ⬢ app_name-20201027... free
Created cleardb-deep-10722 as CLEARDB_DATABASE_URL
Use heroku addons:docs cleardb to view documentation

CLEARDB_DATABASE_URLにDB接続情報がセットされている

$ heroku config:get CLEARDB_DATABASE_URL
mysql://{ユーザー名}:{パスワード}@{ホスト名}/{データベース名}?reconnect=true

DATABASE_URLにMySQLのURLをセットする
mysql://ではなくmysql2://になっているので注意。

$ heroku config:add DATABASE_URL=mysql2://{ユーザー名}:{パスワード}@{ホスト名}/{データベース名}?reconnect=true

config/database.ymlのproductionの箇所を変更

config/database.ymlのproduction
default: &default
  adapter: mysql2
  encoding: utf8mb4
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  username: root
  password:
  host: <%= ENV.fetch("DB_HOSTS") { 'db' } %>

development:
  <<: *default
  database: app_name_development

test:
  <<: *default
  database: app_name_test

production:
  <<: *default
  url: <%= ENV['DATABASE_URL'] %> ##これを追加

4 herokuにRailsAPIプロジェクトをデプロイ。

$ cd <RailsAPIプロジェクト>
$ git init 
$ git add =A
$ git commit -m "first commit"
$ git remote add heroku https://git.heroku.com/アプリ名.git
$ git push heroku master
$ heorku run rails db:migrate --app アプリ名
$ heroku open --app アプリ名 #サイトを開く

5 ターミナルでデータをリクエストを送りデータ通信・保存ができているかテスト

※開発段階でTaskモデルを作成しています。

#Post
$ curl https://アプリ名.herokuapp.com/api/tasks -X POST -d 'task[text]=洗濯する'
create new task.
#Get 
$ curl https://アプリ名.herokuapp.com/api/tasks
[{"id":1,"text":"洗濯する","created_at":"....","updated_at":"...."}]
#Delete
$ curl https://アプリ名.herokuapp.com/api/tasks/1 -X DELETE
destroy a task.

6 RailsにおけるCORS対応

※フロントエンドとのやり取りに必要
Rails側のAPIサーバ側で、CORSに対応していなかったためブラウザ側で受信を拒絶されていたようです。Railsでは gem cyu / rack-coresを使うと、簡単にCORS対応が可能になります。
Gemfileに以下の一行を追加して、bundle installをします

gem 'rack-cors'

次に、config/initializers/cors.rbのコメント部分をコメントアウトします。
originsのところで、許容するオリジンを指定してあげます。
これだけで、APIサーバ側でCORSの設定ができます。

config/initializers/cors.rb
# Be sure to restart your server when you modify this file.

# Avoid CORS issues when API is called from the frontend app.
# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests.

# Read more: https://github.com/cyu/rack-cors

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'フロントエンドアプリのURL'

    resource '*',
      headers: :any,
      methods: [:get, :post, :options]
  end
end
1
0
0

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
1
0