LoginSignup
124
120

More than 3 years have passed since last update.

rails + nginx + unicorn連携

Last updated at Posted at 2014-08-07

1.サンプルアプリ作成

railsサンプルアプリの作成については以下参照

rails環境構築(CentOS + ruby on rails)

2.nginxインストール

# リポジトリファイルの作成
$ sudo vim /etc/yum.repos.d/nginx.repo
# 以下を記載し保存
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/6/$basearch/
gpgcheck=0
enabled=0
# nginxのインストール
$ sudo yum --enablerepo=nginx install nginx
# バージョン確認
$ nginx -v

3.unicorn <-> nginx連携

unicorn側の設定

# アプリ用ユーザに切り替え
$ su - rails
# Gemfileの設定(unicornの行をコメントイン)
$ cd ~/sample/
$ vim Gemfile
# Gemfileより該当unicornのインストール
$ bundle install --path=~/sample/vendor/bundle
# unicorn用ファイル作成
$ vim ~/sample/config/unicorn.rb
# 以下を記載し保存
rails_root = File.expand_path('../../', __FILE__)
 
worker_processes 2
working_directory rails_root
 
listen "#{rails_root}/tmp/unicorn.sock"
pid "#{rails_root}/tmp/unicorn.pid"
 
stderr_path "#{rails_root}/log/unicorn_error.log"
stdout_path "#{rails_root}/log/unicorn.log"

nginx側の設定

# nginx用設定ファイル作成
$ sudo cp /etc/nginx/conf.d/default.conf /etc/nginx/conf.d/sample.conf
$ vim /etc/nginx/conf.d/sample.conf
# 以下のとおりに記載し保存
upstream unicorn {
   # nginxとunicornの連携
   # ↑で作成したunicorn.rbで設定したunicorn.sockを指定
 server unix:/home/rails/sample/tmp/unicorn.sock;
}
 
server {
  listen 80;
  server_name <サーバ名>;
 
  root /home/rails/sample/public;
 
  access_log /var/log/nginx/sample_access.log;
  error_log /var/log/nginx/sample_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;
   }
}
# nginxの起動
$ sudo /etc/init.d/nginx start
# unicornの起動
$ su - rails
$ cd ~/sample/
$ bundle exec unicorn_rails -c config/unicorn.rb -p 3000 -E development -D
# unicorn起動確認
$ ps -ef | grep unicorn | grep -v grep
# ブラウザにて確認
http://<サーバ名>
# unicornの停止
$ kill -QUIT <pid(tmp/unicorn.pidに記載されてる)>
124
120
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
124
120