LoginSignup
74
52

More than 3 years have passed since last update.

Rails5でpuma + nginx連携

Last updated at Posted at 2018-03-29

Rails5で作成したアプリケーションをpuma + nginxで動かすというのをやってみた。

本記事で知ることのできること
・最低限の設定
・躓いたところ
知ることのできないこと
・nginx, pumaの詳細な設定
・セキュリティを意識した設定

環境
・OS Ubuntu16.04
・Rails 5.1.5
・nginx 1.10.3

pumaの設定

今回はsocketでpumaとnginxを連携させるため、Rails.root/config/puma.rbを編集。

# ポートでのlistenは不要なのでコメントアウト
#port  ENV.fetch("PORT") { 3000 }

# socketの設定
# ディレクトリがない場合は作成しておく
bind "unix://#{Rails.root}/tmp/sockets/puma.sock"

この際に、ポートでのlistenはコメントしておかないとsocketのlistenが行われず(pumaの仕様?)ハマった。
参考: https://qiita.com/kappy0322/items/b6c267dfb330a47fea9f

これでpumaを起動すればsocketファイルができ、待受け完了。
rails s -e production

nginxの設定

設定ファイルは大きく2つあるみたい。
nginxの基本的な設定
・/etc/nginx/nginx.conf
各サイト用の設定
・/etc/nginx/sites-available/*

今回は/etc/nginx/sites-available/配下に myapp ファイルを作成し、設定を記述。

upstream puma {
  # pumaの設定で指定したsocketファイルを指定
  server unix:///home/ubuntu/myapp/tmp/sockets/puma.sock;
}

server {
  # nginxが待ち受けしたいポートを指定
  listen 3000 default_server;
  listen [::]:3000 default_server;
  server_name puma;

  location / {
    proxy_read_timeout 300;
    proxy_connect_timeout 300;
    proxy_redirect off;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    # 上記server_name で設定した名前で指定
    proxy_pass http://puma;
  }
}

記述ができたら、設定ファイルのシンボリックリンクを作成。
ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/myapp
次に、nginxの設定ファイルを再読込させる。
nginx -s reload

これで、設定完了。
http://あいぴーあどれす:3000 にアクセスするとnginxが受け、pumaへ回してくれる。

課題
・nginxの設定内容の詳細を理解する

74
52
4

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
74
52