2007-03-30
■ [Ruby][Rails] MongrelをWindowsのサービスとして起動する

昨日の日記でMongrelをインストールしてみたけど、Railsの開発環境のWebサーバとしてMongrelを使う場合は、MongrelをインストールするだけでRailsが勝手にMongrelを起動してくれるようになることがわかったよね。
じゃあつぎはRailsの本番環境として、MongrelをWindowsのサービスとして起動して常駐させてみるよ。まずは、mongrel_serviceをRubyGems Package Managerを使ってインストールするよ。これもコマンド一発、「gem install mongrel_service」でインストールできるよ。
C:\ruby>gem install mongrel_service Need to update 12 gems from http://gems.rubyforge.org ............ complete Select which gem to install for your platform (i386-mswin32) 1. mongrel_service 0.3.1 (mswin32) 2. mongrel_service 0.1 (ruby) 3. Skip this gem 4. Cancel installation > 1 Install required dependency win32-service? [Yn] y Select which gem to install for your platform (i386-mswin32) 1. win32-service 0.5.2 (ruby) 2. win32-service 0.5.2 (mswin32) 3. Skip this gem 4. Cancel installation > 2 Successfully installed mongrel_service-0.3.1-mswin32 Successfully installed win32-service-0.5.2-mswin32 Installing ri documentation for mongrel_service-0.3.1-mswin32... Installing ri documentation for win32-service-0.5.2-mswin32... Installing RDoc documentation for mongrel_service-0.3.1-mswin32... Installing RDoc documentation for win32-service-0.5.2-mswin32... C:\ruby>
ここではmongrel_service-0.3.1-mswin32とwin32-service-0.5.2-mswin32をインストールしてみたよ。
さっそく、こないだ作った掲示板をWindowsサービスとして登録してみるよ。コマンドプロンプトで
mongrel_rails service::install -N "Rails BBS" -c c:\rails\bbs -p 4000 -e production
と入力してね。ちなみに「-N」オプションはサービス名、「-c」オプションはRailsのWebアプリケーションの設置場所、「-p」オプションはポート番号、「-e」オプションはRailsをどのモードで(test、development、production)起動するかを指定するよ。
じゃあ、さっそく起動してみよう!まずは「スタート」「設定」「コントロールパネル」「管理ツール」「サービス」を起動するよ。「Rails BBS」というサービスが追加されているはずだから、右クリックして「開始」を選んでね。状態が「開始」になればOKだよ。
次にhttp://localhost:4000/に接続すると、きちんとRailsのWelcomeページが表示されることが確認できるよ。ちなみにこのWelcomeページはC:\rails\bbs\public以下のコンテンツが表示されているから、自分で書き換えることもできるよ。
その次は、いよいよRailsで作った掲示板のアプリケーションにアクセスしてみるよ。http://localhost:4000/bbsにアクセスすると‥‥。あれ、エラーになっちゃった。
エラーの内容を見ると、本番環境(production)用のデータベースがないみたい。そういえば本番環境用のデータベースを作るのを忘れていたね。プロジェクトのディレクトリに戻って「rake db:migrate RAILS_ENV=production」でデータベースを作成するよ。
C:\rails\bbs>rake db:migrate RAILS_ENV=production (in C:/rails/bbs) == CreateEntries: migrating =================================================== -- create_table(:entries) -> 0.1900s == CreateEntries: migrated (0.2100s) ========================================== C:\rails\bbs>
いったんMongrelのサービスを停止するよ。先ほどの「サービス」の「Rails BBS」を右クリックして「停止」を選んでね。そして、もう一度右クリックして「開始」を選んで起動しなおしてね。
もういちどhttp://localhost:4000/bbsにアクセスすると‥‥。今度はうまくいったよ!
あと、このサービスを削除したくなったら、サービスを停止したあとに
mongrel_rails service::remove -N "Rails BBS"
とすれば削除できるはずだよ。