MacBookAir'11 OSX 10.9 Mavericks でRailsアプリケーションサーバー構築
1. nginxはhomebrewでインストール。
$ brew install nginx
設定は /usr/local/etc/nginx/nginx.conf
に記述する。Mac + unicorn + nginx + Rails - Giworldを参考した。
worker_processes 2; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; upstream unicorn.rails_app { # 自分のrailsアプリの場所 server unix:/Users/kazukitash/ruby_src/jitaku/tmp/sockets/unicorn.sock fail_timeout=0; } server { listen 8080; server_name jitaku-app.com; charset utf-8; location / { alias /Users/kazukitash/ruby_src/jitaku/public; index index.html index.htm index; try_files $uri/index.html $uri.html $uri @unicorn_rails_app; } error_page 500 502 503 504 /50x.html; # location = /50x.html { # root html; # } location @unicorn_rails_app { proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Server $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://unicorn.rails_app; } } }
nginxのコマンドは次の通り。
- 起動
nginx
- 終了
nginx -s stop
- 再起動
nginx -s reload
- 設定の検証
nginx -t
2. 次にunicornをgemで入れる。
$ gem install unicorn
[RAILS_DIR]/config/unicorn.rbを作成し、編集。これもMac + unicorn + nginx + Rails - Giworldを参考した。
#ワーカー数 worker_processes 2 #ソケット経由で通信する listen File.expand_path('tmp/sockets/unicorn.sock', ENV['RAILS_ROOT']) # ログ 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 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 # StGTTOU だと worker_processes が多いときおかしい気がする 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
unicornに必要なgemをGemfileに書く。
group :production do gem 'unicorn' gem 'execjs' gem 'therubyracer' end
bundle install
をしたら以下のコマンドでunicornが起動する。
unicorn_rails -c config/unicorn.rb -E production
デーモンにしたかったら以下のようにする。
unicorn_rails -c config/unicorn.rb -E production -D
ちなみにデーモンにしたときは kill #{pid}
で終了させる。pidはpsで見れる。
ps -ef | grep unicorn_rails
localhost:8080でrailsアプリが表示されたら成功。
参考にしたサイト
Mac + unicorn + nginx + Rails - Giworld nginxにreloadシグナルを送っても設定を再読み込みしてくれなかったりなかなかKILLされなかったり - There’s an echo in my head nginx入門