Rails4をHerokuに(クラウドに一歩一歩近づく)

前回、Google App EngineでGuestbookを作ったので、これと同じことをRuby on Rails 4で、しかもやはりPaaSのHerokuにデプロイしてみました。

まずはRubyを2.0.0にし、Rails4をインストール

もともとrvmを使って、Rubyは2.0.0をインストールしていたのですが、デフォルトではsslに対応していません(Gemfileの1行目のhttpsをhttpに変更すれば良いらしいですが)。したがって、再度インストールし直しました。

Ruby2.0.0-p0

https://gist.github.com/jfirebaugh/4007524
にある、オプション1でインストールしました。すなわち下のよう。

brew update
brew install openssl
brew link --force openssl #これが必要かは不明?
rvm get head
rvm install 2.0.0-p0 --with-openssl-dir=`brew --prefix openssl`
rvm use 2.0.0-p0
ruby --version
ruby 2.0.0p0 (2013-02-24 revision 39474) [x86_64-darwin12.2.1]
Rails 4
gem install rubygems-update
gem -v
2.0.2
rvm --create 2.0.0@rails4
rvm --default use 2.0.0@rails4
gem install rails --version 4.0.0.beta1 --no-ri --no-rdoc

herokuコマンドをインストール

以前は、gemでインストールしていたのですが、現在はHerokuから提供されているので、これをインストールしました。
https://toolbelt.heroku.com/osx
これで、準備は終了。

PostgreSQLのインストールとgem install pg

PostgreSQL9.2

http://www.enterprisedb.com/products-services-training/pgdownload#osx
からダウンロードして、インストール。

gem install pg
export PATH=$PATH:/Library/PostgreSQL/9.2/bin
gem install pg #これではインストールできず
env ARCHFLAGS="-arch x86_64" gem install pg -- --with-pg-config=/Library/PostgreSQL/9.2/bin/pg_config

「/Library/Postgresql/9.2/bin」にパスを通しておいた方が便利。

PostgreSQLの設定

どうやらHerokuでは(実際はよくわかっていない)、DBのユーザを作ったりパスワードを設定したり出来ないように思えるので、ローカルでもアプリケーション名と同じ名前のユーザーで、パスワードなしでアクセスできるようにするために、pg_hba.confを以下のように変更する。

local   all             all                                     trust           
# IPv4 local connections:                                                       
host    all             all             127.0.0.1/32            trust           
# IPv6 local connections:                                                       
host    all             all             ::1/128                 trust           

sudo su postgres -c '/Library/Postgresql/9.2/bin/pg_ctl start -D /Library/Postgresql/9.2/data'


それから、ついでにユーザを作成(前述したように、Herokuではアプリケーション名と同じPostgreSQLユーザが利用されるようなので)、データベースも(ローカルはdevelopment環境なので、「myfirst_development」)を作成する。

psql
create user myfirst CREATEDB CREATEUSER;
create database myfirst_development;

railsコマンドでアプリをひな形を作成

rails new myfirst --edge --database=postgresql  --skip-index-html
...
  Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed.
cd myfirst
rails generate scaffold member guest_name:string content:text created_at:datetime
Heroku にtilt (1.3.5)がないらしい

gem moduleのtilt (1.3.5)がHerokuにないらしく、デプロイしようとするとエラーになるので、myfirstディレクトリーのルートにある「Gemfile.lock」内の

  tilt (1.3.5)

  tilt (1.3.3)

に変更する。

Gemfileの修正
  gem 'rails',     github: 'rails/rails'

gem 'rails', '4.0.0.beta1'
ruby '2.0.0'

に、またunicornを利用するために

  # gem 'unicorn'

のコメントを外します。
そしておきまりの

  bundle install
unicornの設定ファイルunicorn.rb
worker_processes 1
timeout 30
preload_app true

before_fork do |server, worker|
# Replace with MongoDB or whatever
if defined?(ActiveRecord::Base)
ActiveRecord::Base.connection.disconnect!
Rails.logger.info('Disconnected from ActiveRecord')
end

# If you are using Redis but not Resque, change this
old_pid = "#{server.config[:pid]}.oldbin"
    if old_pid != server.pid
      begin
        sig = (worker.nr + 1) >= server.worker_processes ? :QUIT : :TTOU
        Process.kill(sig, File.read(old_pid).to_i)
      rescue Errno::ENOENT, Errno::ESRCH
      end
    end

sleep 1
end

after_fork do |server, worker|
  if defined?(ActiveRecord::Base)
    ActiveRecord::Base.establish_connection 
  end
end
テーブルなどを作成
rake db:migrate
==  CreateMembers: migrating ==================================================
-- create_table(:members)
   -> 0.0062s
==  CreateMembers: migrated (0.0063s) =========================================
config/routes.rb

にrootを追加

Myfirst::Application.routes.draw do
  resources :members
  root :to => "members#index"
ローカルで確認
bundle exec unicorn_rails -E development -c config/unicorn.rb

git
git init
git add .
git commit -m 'initial commit'
herokuアプリの新規作成

herokuのメンバー登録が終わっていない場合は、http://www.heroku.com/に行って、登録を済ませます(実に簡単に登録でいます!)。
また「herokuコマンド」は初回のみメールアドレスとパスワードを聞いています。

heroku create myfirst20130308

これでHerokuにおけるアプリの新規作成は終了。

herokuへのデプロイ
git push heroku master
heroku run rake db:migrate
サーバでの確認

http://myfirst20130308.herokuapp.com/
で、ローカルと同様に確認できます。