LoginSignup
8
7

More than 5 years have passed since last update.

rails+unicorn+nginxで環境構築

Last updated at Posted at 2016-06-12

yumをアップデート

yum -y update

必要なもろもろをインストール

yum install -y curl-devel sqlite-devel libyaml-devel
yum install -y nodejs
gem install bundler rails

nginxをインストール

yum install -y nginx

unicornをインストール

gem install unicorn

ここではrails_appが以下にあるものとします。

/usr/share/nginx/html/rails_app

unicorn.rbを編集

config/unicorn.rb
# -*- coding: utf-8 -*-
worker_processes Integer(ENV["WEB_CONCURRENCY"] || 2)
timeout 15
preload_app true  # 更新時ダウンタイム無し

listen "/tmp/sockets/unicorn.sock"
pid "/tmp/sockets/unicorn.pid"

before_fork do |server, worker|
  Signal.trap 'TERM' do
    puts 'Unicorn master intercepting TERM and sending myself QUIT instead'
    Process.kill 'QUIT', Process.pid
  end

  defined?(ActiveRecord::Base) and
    ActiveRecord::Base.connection.disconnect!
end

after_fork do |server, worker|
  Signal.trap 'TERM' do
    puts 'Unicorn worker intercepting TERM and doing nothing. Wait for master to send QUIT'
  end

  defined?(ActiveRecord::Base) and
    ActiveRecord::Base.establish_connection
end

# ログの出力
stderr_path File.expand_path('log/unicorn.log', ENV['RAILS_ROOT'])
stdout_path File.expand_path('log/unicorn.log', ENV['RAILS_ROOT'])

上記のようにするとログはプロダクション環境の場合

tail -f /usr/share/nginx/html/rails_app/log/production.log

で見ることができます。

Nginxの設定ファイルを編集

vi /etc/nginx/conf.d/default.conf

もしtmp配下にsocketsフォルダがないときには

mkdir /tmp/sockets

で作成

default.conf
upstream app {
    # unicorn.rbで設定したもの
    server unix:/tmp/sockets/unicorn.sock fail_timeout=0;
}

server {


    listen 80;
    server_name localhost;

    # rails_appの場所
    root /usr/share/nginx/html/rails_app/public;

    try_files $uri/index.html $uri @app;

    location @app {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://app;
    }

    error_page 500 502 503 504 /500.html;
    client_max_body_size 4G;
    keepalive_timeout 10;
}  

Nginxを再起動

service nginx restart

unicornをスタートさせる

unicorn_rails -c config/unicorn.rb -E production -D

ブラウザ上で動作確認

http://your_ip_address/whatever

起動中のunicornを確認

ps aux | grep unicorn

起動中のunicornをkill

kill -QUIT `cat /tmp/sockets/unicorn.pid`
8
7
0

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
8
7