Railsデプロイで困ったことメモ
調べながら解決していったので、自分の詰まったところとそのリンクのまとめに近い。
やっていること
環境
- nginx
- Ruby on Rails 5
- puma
Rails側設定
/config/environments/production.rb
SSLの強制、/publicの公開、サイトのトップページをサブディレクトリに。
config.force_ssl = true config.public_file_server.enabled = true ENV["RAILS_RELATIVE_URL_ROOT"] = "/siteA" Rails.application.config.relative_url_root = "/siteA"
/config.ru
サブディレクトリで起動するように変更。
require_relative 'config/environment'
map ActionController::Base.config.relative_url_root || "/" do
run Rails.application
end
/config/puma.rb
ここで、nginxで振り分けるsockを生成する設定。 ポート番号もアプリごとに分ける。
_app_path = "#{File.expand_path("../..", __FILE__)}"
_app_name = File.basename(_app_path)
_home = ENV.fetch("HOME") { "/home/アプリケーションのディレクトリ" }
pidfile "#{_home}/run/#{_app_name}.pid"
bind "unix://#{_home}/run/#{_app_name}.sock"
daemonize true
directory _app_path
port ENV.fetch("PORT") { ポート番号をアプリごとに設定 }
nginx側設定
設定ファイルをいじり、サブディレクトリをRailsのアプリケーションのポートに振り分ける。 Rails側のタイムアウトの時間設定はproxyのタイムアウトで設定するのが注意どころ。
upstream siteA {
server unix:///home/~/run/~.sock fail_timeout=0;
}
upstream siteB {
server unix:///home/~/run/~.sock fail_timeout=0;
}
server {
listen 80;
server_name www.example.com;
return 301 https://$host$request_uri;
}
server {
server_name www.example.com;
listen 443 default ssl;
ssl on;
ssl_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem;
location /pll {
proxy_pass http://siteA;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Proto https;
proxy_redirect off;
}
location /hateconcat {
proxy_pass http://siteB;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Proto https;
proxy_redirect off;
}
location / {
root /var/www/html;
index index.html;
}
error_page 500 502 503 504 /500.html;
client_max_body_size 4G;
proxy_connect_timeout 605;
proxy_send_timeout 605;
proxy_read_timeout 605;
send_timeout 605;
keepalive_timeout 605;
}
問題と解決のリンク
サブディレクトリへの展開
An unhandled lowlevel error occurred.
このようなエラーはSECRET_KEY_BASEが無いときに出ることが多いらしい。 起動時に環境変数を渡してあげる。
puma_error.logで確認できるのでわかりやすい。
Assetsをプリコンパイルしても、404エラーが出る。
プロダクション環境ではデフォルトでは、public/を公開しない。おそらくnginxなどに委ねることもできるからだと思う。