LoginSignup
30
23

More than 5 years have passed since last update.

Rails に静的ファイルの配信をお願いする

Last updated at Posted at 2016-06-03

概要

config/environments/production.rb : L25 のコメント内容をよく見て、Apache やNginx 配下で動かしましょうね、という話し

前提状況

  • アプリケーション テンプレート機能を利用したRails の初期化ができる
  • gouf/dotfiles/.rails_application_template.rb - GitHub (アプリケーション テンプレート)を利用してアプリケーションを初期化( rails new $PROJECT_DIR)
  • テンプレートはbootstrap 適用済みの状態でプロジェクトを作成してくれる
  • Apache やNginx は登場しない
  • サンプル アプリケーションとして動作させるためにコマンドいろいろ叩く
rails g scaffold user name:string
rake db:migrate
rake assets:precompile

問題

rails s して開発環境としてサーバを起動させると、bootstrap が適用された状態で起動する

しかし、rails s -e production で、プロダクション環境としてサーバを起動させると、bootstrap が適用されない

原因

  • log/production.log を観察してみると、静的ファイルに対して、No Route Match エラーが発生していた
log/production.log
F, [2016-06-02T07:06:44.055266 #8812] FATAL -- : $                                                  
   7 ActionController::RoutingError (No route matches [GET] "/javascripts/application.js")
  • そもそもとして、Apache やNginx 配下でproduction 環境を動作させていない
  • config/environments/production.rb の設定
Rails.application.configure do
  # ...

  # Disable serving static files from the `/public` folder by default since
  # Apache or NGINX already handles this.
  config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?

  #...
end

「Rails のやることじゃないよ」って書いてあった...

解決

rails -e production にシェル変数を加えて起動してあげる

rails -e production RAILS_SERVE_STATIC_FILES=true

(ENV[...] 部分を削除して直接true に書き換えると、環境変数による制御が、外部からの制御がむつかしくなるので、それはよくない)

まとめ・注意点

ログ見るのだいじ

開発環境で直接Apache or Nginx を動かすようにするか、docker-compose を利用して同様に、config.serve_static_filesfalse でも動くように環境を整備したい

30
23
0

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
30
23