Ruby on Rails 在佈署上面,有兩種模型:出自ihower.tw
Passenger 又叫做 mod_rails,是目前佈署 Ruby on Rails 最方便的方式,直接將對 Rails 的支援變成 Apache 或 Nginx 的模組,就像 mod_php 一樣。
Apache 是一套功能非常豐富、非常多人使用的開放原始碼 HTTP 伺服器,要在 Ubuntu 上安裝 Apache + Passenger 指令如下:
sudo apt-get install -y apache2-mpm-prefork apache2-prefork-dev libapr1-dev libaprutil1-dev sudo gem install passenger sudo passenger-install-apache2-module
執行完 passenger-install-apache2-module 後會有一段設定,請將此設定加入 /etc/apache2/conf.d/mod_rails 檔案之中,例如:
passenger_module /usr/local/lib/ruby/gems/1.8/gems/passenger-2.2.15/ext/apache2/mod_passenger.so PassengerRoot /usr/local/lib/ruby/gems/1.8/gems/passenger-2.2.15 PassengerRuby /usr/local/bin/ruby
假設你的 Rails 專案放在 /home/ihower/your_rails_app 目錄下,那麼可以新增 /etc/apache2/sites-enabled/your_rails_app.conf 這個專案的設定,例如:
<VirtualHost *:80> ServerAdmin [email protected] ServerName your_rails_app.ruby.tw DocumentRoot /home/ihower/your_rails_app/public ErrorLog /var/log/apache2/error-your_rails_app.log CustomLog /var/log/apache2/access-your_rails_app.log combined # Deflate AddOutputFilterByType DEFLATE text/html text/xml text/plain text/css application/x-javascript text/javascript; BrowserMatch ^Mozilla/4 gzip-only-text/html BrowserMatch ^Mozilla/4\.0[678] no-gzip BrowserMatch \bMSIE !no-gzip !gzip-only-text/html <Directory "/home/ihower/your_rails_app/public"> Options FollowSymLinks Order allow,deny Allow from all AllowOverride all Options -MultiViews FileETag none </Directory> </VirtualHost>
注意到 DocumentRoot 和 Directory 是指向 public 這個靜態檔案的目錄。設定好之後,執行 sudo apache2ctl restart 便會啟用。如果之後你的 Rails 有任何修改要重新載入,但是並不想把 Apache 重開,請在你的 Rails 應用程式目錄下執行 touch tmp/restart.txt,這樣 mod_rails 就會知道要重新載入 Rails,而不需要重開 Apache。
Nginx 則是另一套在 Rails 世界上還蠻常被使用的第二選擇,相較於 Apache 雖然功能較少,但執行效率更為良好。要讓 Nginx 裝上 Passgener 不需要先裝 Nginx,只需要執行以下指令:
sudo passenger-install-nginx-module
這是因為 Passenger 必須與 Nginx 一起編譯安裝的關係,所以 Passenger 的安裝指令就包括了安裝 Nginx。
反向代理(Reverse proxy)模型就比較複雜了,它分成 Web 伺服器和 Application 伺服器,圖示如下:
其中 Web 伺服器會是 Apache 或 Nginx,但是它除了提供靜態檔案之外,其餘的任務就只是做 reverse proxy 將 request 分發到 Application 伺服器。
而 Application 伺服器負責執行 Ruby on Rails 程式,這有不少選擇:
相較於 Passenger,設定上會比較複雜。
(TODO) 參考 Does Rails Performance Need an Overhaul? 這一篇文章
可以參考這篇文章 The Best Ruby on Rails Hosting Services ,這些服務可以概分為:
相較於 PHP,Rails 的確是比較耗費資源的,所以會推薦 VPS 等級以上。
以上的租用方式都是以月來計算,比較沒有彈性。如果需要以小時計算、租用資源非常彈性的服務,那就是雲端了:
$ heroku keys:add "%homedrive%%homepath%/.ssh/id_rsa.pub"
(TODO) 請參考這篇文章 Why? 主動攔截 Rails exception 錯誤
(TODO) NewRelic