これから始める Ruby on Rails シリーズRuby on RailsアプリをHerokuにデプロイしてみる
はじめに
前回のRuby on Railsの最初の一歩ではRuby on Railsの環境構築について学習しました。今回はHerokuというPaasを利用してアプリケーションをデプロイするところまで勉強します。アプリケーションの作成は行わず、rails newで自動作成されるデータをHerokuにデプロイし、ブラウザでチェックできることをゴールとします。
Herokuとは
HerokuはRuby on RailsのWebアプリケーションプラットフォームです(Ruby on Rails以外も利用できます)。デプロイ方法はgitで管理しているリポジトリをHerokuのリモートリポジトリにpushすることで行います。サーバー環境を自分で構築する必要がないので、非常に手軽に利用できます。無料版の場合スペックは制限されたものですが勉強には十分でしょう。
Herokuのアカウントを作る
まずは無料で登録できるのでHerokuのアカウントを作っておいてください。Herokuの登録後、専用のツールをインストールするよう指示されるので、そこまで完了させましょう。
環境の準備
前回とほぼ同じ作業となりますが、Herokuを前提としたRuby on Railsの環境を作ります。
ディレクトリを作る
前回とは別のディレクトリを作ります。
$ mkdir deploy.heroku.rails
$ cd deploy.heroku.rails
 rbenvでRubyのバージョンを指定
rbenvでRubyのバージョンを指定しておきましょう。
$ rbenv local 2.1.0
$ rbenv local
2.1.0
 bundlerでGemのパッケージ管理
bundlerを使ってGemを用意します。$ bundle initでGemfileを作ります。
$ bundle init
Writing new Gemfile to /Users/xxx/Projects/Labs/deploy.heroku.rails/Gemfile
 Railsを有効化する
Gemfileを編集してRailsのコメントを外します。
$ vi Gemfile
 変更後のGemfile
# A sample Gemfile
source "https://rubygems.org"
gem "rails"
 Gemのインストール
$ bundle install ...でGemをインストールしましょう。 コマンドオプションに--path vendor/bundleを指定します。
$ bundle install --path vendor/bundle
etching gem metadata from https://rubygems.org/...........
Resolving dependencies...
Installing rake 10.3.2
Installing i18n 0.6.11
Using json 1.8.1
Installing minitest 5.4.1
...
Your bundle is complete!
Gems in the group production were not installed.
It was installed into ./vendor/bundle
 Railsアプリの作成
次にrails newでRailsアプリを作成します。--slip-bundleはすでにbundleを利用済みなので、スキップさせます。その影響で途中でGemfileを上書きするか聞かれますが、enterを押して続行します。
$ bundle exec rails new . --skip-bundle
       exist
      create  README.rdoc
      create  Rakefile
      create  config.ru
      create  .gitignore
    conflict  Gemfile
Overwrite /Users/xxxx/Projects/Labs/deploy.heroku.rails/Gemfile? (enter "h" for help) [Ynaqdh]
       force  Gemfile
      create  app
      create  app/assets/javascripts/application.js
      create  app/assets/stylesheets/application.css
      create  app/controllers/application_controller.rb
      create  app/helpers/application_helper.rb
      create  app/views/layouts/application.html.erb
      create  app/assets/images/.keep
      create  app/mailers/.keep
      create  app/models/.keep
      create  app/controllers/concerns/.keep
      create  app/models/concerns/.keep
      create  bin
      create  bin/bundle
      create  bin/rails
      create  bin/rake
      create  config
      create  config/routes.rb
      create  config/application.rb
      create  config/environment.rb
      create  config/secrets.yml
      create  config/environments
      create  config/environments/development.rb
      create  config/environments/production.rb
      create  config/environments/test.rb
      create  config/initializers
      create  config/initializers/assets.rb
      create  config/initializers/backtrace_silencers.rb
      create  config/initializers/cookies_serializer.rb
      create  config/initializers/filter_parameter_logging.rb
      create  config/initializers/inflections.rb
      create  config/initializers/mime_types.rb
      create  config/initializers/session_store.rb
      create  config/initializers/wrap_parameters.rb
      create  config/locales
      create  config/locales/en.yml
      create  config/boot.rb
      create  config/database.yml
      create  db
      create  db/seeds.rb
      create  lib
      create  lib/tasks
      create  lib/tasks/.keep
      create  lib/assets
      create  lib/assets/.keep
      create  log
      create  log/.keep
      create  public
      create  public/404.html
      create  public/422.html
      create  public/500.html
      create  public/favicon.ico
      create  public/robots.txt
      create  test/fixtures
      create  test/fixtures/.keep
      create  test/controllers
      create  test/controllers/.keep
      create  test/mailers
      create  test/mailers/.keep
      create  test/models
      create  test/models/.keep
      create  test/helpers
      create  test/helpers/.keep
      create  test/integration
      create  test/integration/.keep
      create  test/test_helper.rb
      create  tmp/cache
      create  tmp/cache/assets
      create  vendor/assets/javascripts
      create  vendor/assets/javascripts/.keep
      create  vendor/assets/stylesheets
      create  vendor/assets/stylesheets/.keep
 サーバーを起動してみる
ここまでの状態で、サーバーが立ち上がるか確認してみましょう。
$ bundle exec rails server
Could not find gem 'spring (>= 0) ruby' in the gems available on this machine.
Run `bundle install` to install missing gems.
 なにやら怒られているようです。そんなときは$ bundle updateを実行してみてください。
 アップデートが完了したらもう一度サーバーを起動してみます。
$ bundle exec rails server
=> Booting WEBrick
=> Rails 4.1.6 application starting in development on http://0.0.0.0:3000
=> Run `rails server -h` for more startup options
=> Notice: server is listening on all interfaces (0.0.0.0). Consider using 127.0.0.1 (--binding option)
=> Ctrl-C to shutdown server
[2014-09-15 17:41:23] INFO  WEBrick 1.3.1
[2014-09-15 17:41:23] INFO  ruby 2.1.0 (2013-12-25) [x86_64-darwin13.0]
[2014-09-15 17:41:23] INFO  WEBrick::HTTPServer#start: pid=18011 port=3000
 http://127.0.0.1:3000/にアクセスしてRuby on Railsの画面が表示されれば成功です。
Gitの設定
Herokuにデプロイするためにgitが必要になるので$ git initしてcommitしましょう。今回bundlerを使っているので$ git add . する前に.gitignoreファイルにvendor/を追加しておいてください(.gitignoreファイルはbundle exec rails new .の段階で作られています)。
$ git init
Initialized empty Git repository in /Users/xxx/Projects/Labs/deploy.heroku.rails/.git/
$ git add --all
$ git commit -m 'first commit'
 Gemfileの調整
Herokuにデプロイするために、先ほど作ったGemfileに手を加えます。まず、全体のソースが以下です。2行目のruby 2.1.0と8,9,10行目のgroup :development do ...に最後のgroup :production do ...が追加対象です。
group :development do ... endは開発環境で利用するGemです。逆にgroup :production do ... endはHeroku環境のみで利用するGemとなります。
source 'https://rubygems.org'
ruby '2.1.0'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.1.6'
# Use sqlite3 as the database for Active Record
group :development do
  gem 'sqlite3'
end
# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.3'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer',  platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0',          group: :doc
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring',        group: :development
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
# Use debugger
# gem 'debugger', group: [:development, :test]
# production
group :production do
  gem 'pg'
  gem 'rails_12factor'
end
 Gemの再インストール
Herokuに合わせたGemfileの修正が完了したら--without productionを含めて$ bundle installを行います。--without productionはHeroku用のGemをローカルにインストールさせないようにするためのものです。
 $ bundle install --path vendor/bundle --without production
 Fetching gem metadata from https://rubygems.org/..........
Resolving dependencies...
Your bundle is complete!
Gems in the group production were not installed.
It was installed into ./vendor/bundle
 Herokuにデプロイするためにコミットする
ここまでの状態をHerokuにデプロイするためにコミットします。
$ git add --all
$ git commit -m 'Gemfile update'
 Herokuのセットアップ
それでは、Herokuの準備に移りましょう。
Herokuにログイン
Herokuにログインします。アカウント登録済みのメールアドレスとパスワードを入力します。
$ heroku login
Enter your Heroku credentials.
Email: your@com
Password (typing will be hidden):
Authentication successful.
 Heroku上にアプリ環境を作成する
アプリケーション環境をコマンドで構築します。
$ heroku create
Creating protected-earth-7454... done, stack is cedar
http://protected-earth-7454.herokuapp.com/ | git@heroku.com:protected-earth-7454.git
Git remote heroku added
 Herokuにデプロイ
ではgit pushを使ってHerokuにデプロイします。 エラーが出る場合は、Herokuに公開鍵を正しく登録できているか確認しましょう。
$ git push heroku master
Warning: Permanently added the RSA host key for IP address 'xxx.xxx.xxx.xxx' to the list of known hosts.
Initializing repository, done.
Counting objects: 65, done.
Delta compression using up to 4 threads.
 ブラウザでチェック
ブラウザチェックもコマンドを打つことで、自動でブラウザが立ち上がり確認用ページを表示してくれます。
$ heroku open
 表示される画面
以下のように表示されていればデプロイ成功です。

以上がHerokuへのデプロイ手順です。単純にデプロイするだけであれば、それほど難しいものではありませんね。次はローカル環境を使ってRuby on Railsについて勉強しようと思います。