Vagrant上でNginx+Unicornサーバー設定
rails serverコマンドでアプリケーションサーバーを立ち上げるのも手間になってきたので、Unicornを入れてみました。 こちらは前回記事の続きの作業になります。
Unicornをインストール
- 以下、Vagrant内での作業になります。
- Gemインストールをおこなう
gem install unicorn
- bundle installをおこなう
$ cd /vagrant/myapp # プロジェクトディレクトリ $ vi Gemfile gem 'unicorn' # 書き足す $ bundle install
- unicorn.rbコンフィグの作成
$ vi /vagrant/myapp/config/unicorn.rb # 以下のような内容で新規作成する rails_root = File.expand_path('../../', __FILE__) rails_env = ENV['RAILS_ENV'] || "development" worker_processes 2 working_directory rails_root listen "/tmp/#{rails_env}_unicorn.sock" pid "/tmp/#{rails_env}_unicorn.pid" stderr_path "#{rails_root}/log/#{rails_env}_unicorn_error.log" stdout_path "#{rails_root}/log/#{rails_env}_unicorn.log"
- Nginx側設定
- conf作成
$ vi /etc/nginx/site_avabable/virtualhost-myapp.conf # nginx.confでincludeされる upstream unicorn { server unix:/tmp/development_unicorn.sock; } server { listen 80; server_name {指定ドメイン}; root {RAILS_ROOT}/public; access_log {LOG_PATH}/access.log; error_log {LOG_PATH}/error.log; client_max_body_size 100m; error_page 500 502 503 504 /500.html; try_files $uri/index.html $uri @unicorn; 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; } } $ ln -s /etc/nginx/site_avabable/virtualhost-myapp.conf /etc/nginx/site_enable/virtualhost-myapp.conf $ sudo service nginx restart
- Uniornを起動
$ bundle exec unicorn -D -c config/unicorn.rb -E development
$ sudo vi /etc/hosts # VagrantIPアドレスと指定ドメインをスペースで区切り記載 # グローバルに存在するドメインを記載すると、アクセスがVagrantに向いてしまうので注意! 192.168.33.101 {指定ドメイン}
コンフィグ等はこちらの記事にあったものを少し書き換えました。 - Rails4.2 を Nginx + Unicorn で動作させる - Shred IT!!!! - rails + nginx + unicorn連携 - Qiita
動作確認方法
$ ps aux|grep unicorn
developmentなんで開発系までですが、ざっくり動作しました。