本文章的 code 可參考公開的 pull request
https://github.com/5fpro/cupid/pull/11/files
這是基礎到不行的設定方式,考量到 server 效能在設定上的 best practice 將會在日後持續 update 本文。
安裝 gem
Gemfile1
2
3
4
5
| group :development do
gem 'capistrano-unicorn', :require => false
end
gem 'unicorn'
|
本文所採用的 gem 版本
Gemfile.lock1
2
| capistrano-unicorn (0.1.9)
unicorn (4.6.2)
|
佈署設定
這裡的 production.rb 是針對 rails_env=production,而非 capistrano 中 multistage 的 production
config/unicorn/production.rb1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| worker_processes 1
preload_app true
listen '/tmp/unicorn.cupid.sock' # sock 檔名可依照 app 需求設定
stderr_path 'log/unicorn.error.log'
stdout_path 'log/unicorn.log'
pid "tmp/pids/unicorn.pid"
rails_env = ENV['RAILS_ENV'] || 'production'
# before/after fork 可自行擴充
before_fork do |server, worker|
end
after_fork do |server, worker|
end
|
(也可以把上述檔案放在 config/unicorn.rb)
server 上的 nginx.conf
nginx.conf1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
| upstream my_app { # upstream 名稱可自定
server unix:/tmp/unicorn.cupid.sock; # 這裡要和 config/unicorn/production.rb 中 listen 的設定對應
}
server {
listen 80;
server_name example.com;
# passenger_enabled on; # 原本要設定 passenger 的記得要拿掉
# .......
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_pass http://my_app; # upstream 名稱
}
location ~ ^/(assets)/ { # 這裡是 precompile 後的 assets file 路徑
gzip_static on; # to serve pre-gzipped version
expires max;
add_header Cache-Control public;
}
# .......
}
|
把 unicorn 重啟的 hook 掛到 deploy.rb 中
config/deploy.rb1
2
| require 'capistrano-unicorn'
after 'deploy:restart', 'unicorn:restart'
|
done!
如何在本機測試 unicorn
bundle exec unicorn
Go to http://localhost:8080
參考資料