Nginx + Unicornで複数のRailsアプリケーションをサブディレクト形式で起動

事前にサーバ準備は完了している前提

サーバはubuntuを使用

  • Railsプロジェクトの作成
  • nginxのインストール
  • unicornのインストール(Railsプロジェクトの中のgem)

構成

インターネット == Nginx == [unicorn - Rails App]
アクセスをNginxが管理し、各アプリケーション等(unicorn)へ振り分ける

Nginxの設定

/etc/nginxにあるnginx.confがNginxの全体設定ファイル。さらに、そこから詳細設定ファイルをconf.d/(もしくはsite-enable)をインクルードしている。

conf.dmyapp.confを作成し、設定を記述。 unicornとの接続にはunixソケットを利用するため、ソケット部分はnginxとunicornの設定ファイルで揃えること。

# unixソケット、Railsの/tmpあたりに設定する
upstream unicorn {
  server unix:/[path_to_rails_root]/tmp/unicorn.sock fail_timeout=0;
}

server {
  listen 80;
  server_name xxx.xxx.xxx.xxx;

  # ここでサブディレクト形式で設定
  # unicorn起動コマンドにも使用
  location /app1 {
    alias /[path_to_rails_root];
    try_files $uri/index.html $uri.html $uri @unicorn;
  }

  location ~ ^/assets/(.*) {
    alias /[path_to_rails_root]/public/assets/$1;
  }

  location @unicorn {
    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://unicorn;
  }
}

# 複数のアプリケーションを立てるなら、同様にしてupstream, serverを記述する
upstream {
}

server {
}

Nginxの起動

sudo nginx -t #nginxの設定ファイル構文テスト
sudo service nginx start

unicornの設定

/[path_to_rails_root]/tmp/unicorn.rbに記述。

working_directory '/[path_to_rails_root]'

# Unicorn PID file location
# pid '/path/to/pids/unicorn.pid'
pid '/[path_to_rails_root]/tmp/pids/unicorn.pid'

# Path to logs
stderr_path '/[path_to_rails_root]/log/unicorn.log'
stdout_path '/[path_to_rails_root]/log/unicorn.log'

# Unix socket
listen '/[path_to_rails_root]/tmp/unicorn.sock'

# Number of processes
worker_processes 2

# Time-out
timeout 30

config.ruを削除

Rails_rootにあるconfig.ruを削除しないと動作できないことある。削除しても恐らくRailsが作成してくれる。

unicornの起動

別途、起動、停止、再起動のスクリプトを書くべし。

bundle exec unicorn_rails -c config/unicorn.rb -D --path /app1

アップデート中、本当にいつも苦戦する。。

参考|http://qiita.com/iriya-ufo@github/items/0c2122550e69d9b0aff6