rails6 nginx + pumaを使用する

rails6でnginx + pumaを使用するまでの手順を記述してます。nginxのバージョンは1.18.0を使用してます。
環境
- OS CentOS Linux release 7.9.2009 (Core)
- Ruby 2.7.2
- Rails 6.1.1
- nginx 1.18.0
- rbenv 1.1.2-40-g62d7798
puma設定
まずは、railsのwebアプリケーションサーバーである「puma」を設定します。
「config」ディレクトリ配下にある「puma.rb」を以下のように編集します。
1 2 |
#port ENV.fetch("PORT") { 3000 } bind "unix://#{Rails.root}/tmp/sockets/puma.sock" |
これで、pumaのsockファイルのパスが指定できます。
UNIXドメインソケットによるプロセス間の通信となるため
「port ENV.fetch(“PORT”) { 3000 }」はコメントアウトしておきます。
設定が終われば、pumaをproduction環境で起動すれば
「tmp/sockets/puma.sock」が作成されます。
1 |
rails s -e production |
puma.sockが作成される。

nginx設定
「/etc/nginx/conf.d」に任意の名前で「forpuma.conf」というファイルを以下の名称で作成します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# log directory error_log /home/username/rails-project/log/nginx.error.log; access_log /home/username/rails-project/log/nginx.access.log; server { listen 80; server_name xxx.xxx.xxx.xxx; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://unix:/home/username/rails-project/tmp/sockets/puma.sock; } } |
「/etc/nginx」ディレクトリ配下にある「nginx.conf」のユーザーを変更しておきます。ここでは、railsの実行ユーザーに変更してます。
※これをやらないと権限でエラーとなります。
「nginx.conf」を編集します。
1 2 3 4 5 |
user username; or user root; |
port80を使用する場合は、デフォルトの方のポートを変更しておきます。
「/etc/nginx/conf.d/default.conf」
1 2 |
server { listen 81 default_server; |
nginxを再起動します。
1 |
sudo systemctl restart nginx |
確認
先にプリコンパイル処理を実行しておきます。
1 2 |
rails tmp:cache:clear rails assets:precompile |
railsを起動します。
1 |
rails s -e production |
これで、ブラウザから http://server_nameに指定したIPにアクセスすると、railsのTOPページが表示されます。
1対多(rails)
nginxが1つに対して、railsを複数設定する場合はnginxのラウンドロビンを使用することで可能になります。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
upstream railsapp { server unix:/home/username/rails-project/tmp/sockets/puma.sock; server unix:/home/username/rails-project2/tmp/sockets/puma.sock; } server { listen 80; server_name 192.168.100.67; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://railsapp; } } |
ipごとに切り分ける場合は「ip_hash;」を追加します。
1 2 3 4 5 |
upstream railsapp { ip_hash; server unix:/home/username/rails-project/tmp/sockets/puma.sock; server unix:/home/username/rails-project2/tmp/sockets/puma.sock; } |
-
前の記事
javascript this使用時にエラー「Uncaught TypeError: Cannot set property ‘xxx’ of undefined」が発生した場合 2021.03.24
-
次の記事
rails6 EXCELファイルの内容をフロントに表示する 2021.03.24
コメントを書く