Skip to content

Instantly share code, notes, and snippets.

@kazu69
Last active December 12, 2015 09:28
Show Gist options
  • Save kazu69/4752198 to your computer and use it in GitHub Desktop.
Save kazu69/4752198 to your computer and use it in GitHub Desktop.
rails+nginx+unicorn local develop env setting memo ref: http://oblog.objectclub.jp/nginxweb-5
# ngix を起動して
$sudo nginx
# unicorn, nginx 設定後にポート番号指定してunicorn起動
$bundle exec unicorn_rails -l 3000 -l 3001
# 終了は unicorn は cmd + c
# nginx は
$sudo nginx -s stop
# Your gem file Settings to take effect
# Use unicorn as the app server
gem 'unicorn'
# and bundle install Gem
# /usr/local/etc/nginx/nginx.conf
worker_processes 1;
error_log logs/error.log;
pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
access_log logs/access.log;
sendfile on;
keepalive_timeout 65;
# 複数のサーバーに対してアクセスを振り分ける場合は HttpUpstreamModule モジュールを用いる
# backend
upstream backend {
# サーバー名 localhost
server localhost:3000;
server localhost:3001;
}
server {
listen 80;
server_name localhost;
location / {
root /PATH/TO/YOUR/RAILS-APP-PATH;
if (-f $request_filename) { break; }
# 転送先に対してリバースプロキシとして動作している nginx の IP アドレスではなく、
# nginx に対してアクセスがあった IP アドレスをHTTPヘッダにセットしています。
proxy_set_header X-Real-IP $remote_addr;
# nginx に対するアクセスを何処に転送するか
# http を含めたフルパスを記述する必要があり
proxy_pass http://backend;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
}
}
}
application = 'YOUR-APP-NAME'
port = 3000
# この設定は後でnginxで使用する
listen "/tmp/unicorn_#{application}.sock", :backlog => 64
listen port, :tcp_nopush => true
pid "tmp/pids/unicorn.pid"
# ワーカーの数
worker_processes 2
# ログファイル
stderr_path File.expand_path('log/unicorn.log', ENV['RAILS_ROOT'])
stdout_path File.expand_path('log/unicorn.log', ENV['RAILS_ROOT'])
# タウンタイムなくす
preload_app true
# For RubyEnterpriseEdition: http://www.rubyenterpriseedition.com/faq.html#adapt_apps_for_cow
if GC.respond_to?(:copy_on_write_friendly=)
GC.copy_on_write_friendly = true
end
before_fork do |server, worker|
defined?(ActiveRecord::Base) and ActiveRecord::Base.connection.disconnect!
old_pid = "#{server.config[:pid]}.oldbin"
unless old_pid == server.pid
begin
Process.kill :QUIT, File.read(old_pid).to_i
rescue Errno::ENOENT, Errno::ESRCH
end
end
end
after_fork do |server, worker|
defined?(ActiveRecord::Base) and ActiveRecord::Base.establish_connection
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment