Heroku+Railsの高速化

こんばんわ。

Herokuに乗っけてる自分のサービスを3Gで見たとき、
読み込み遅すぎて発狂しました。


対策、何個かやってみたメモ。

Unicorn導入

Gemfileにunicornを追加

group :production
    gem 'unicorn'
end

config/unicorn.rbを作成

 worker_processes Integer(ENV["WEB_CONCURRENCY"] || 3)
 timeout 15
 preload_app true

 before_fork do |server, worker|

   Signal.trap 'TERM' do
     puts 'Unicorn master intercepting TERM and sending myself QUIT instead'
     Process.kill 'QUIT', Process.pid
   end

   defined?(ActiveRecord::Base) and
     ActiveRecord::Base.connection.disconnect!
 end 

 after_fork do |server, worker|

   Signal.trap 'TERM' do
     puts 'Unicorn worker intercepting TERM and doing nothing. Wait for master to send QUIT'
   end

   defined?(ActiveRecord::Base) and
     ActiveRecord::Base.establish_connection
 end

起動のためのProcfile作成

 web: bundle exec unicorn -p $PORT -c ./config/unicorn.rb

Precompileをちゃんとやる

今までPrecompileエラーを適当に放置してて
config/environments/production.rb

config.assets.compile = true

とかやってました...。
ちゃんとやります(^o^ )


私の場合、ViewのLayoutで

<%= stylesheet_link_tag "application", :media => "all" %>
<%= stylesheet_link_tag params[:controller] %>
<%= javascript_include_tag "application" %>
<%= javascript_include_tag params[:controller] %>

と記述してるので
params[:controller]に対応するassets fileは個別にprecompileします

config/environments/production.rb

config.assets.compile = false
config.assets.precompile += %w(foo.css)
config.assets.precompile += %w(bar.css)

config.assets.precompile += %w(foo.js)
config.assets.precompile += %w(bar.js)


あとは、precompileして

% RAILS_ENV=production bundle exec rake assets:precompile

デプロイして

% git add ./
% git commit -a
% git push heroku production

おしまい。
まだ速度に不満があるので何かやらねば・・・

Heroku

Heroku

  • 作者: Neil Middleton,Richard Schneeman
  • 出版社/メーカー: Oreilly & Associates Inc
  • 発売日: 2013/07/22
  • メディア: ペーパーバック
  • クリック: 2回
  • この商品を含むブログを見る