0

前提・実現したいこと

世界一丁寧なAWS解説を参考にしながら、
ローカルで開発したRuby on Railsで作ったサイトを、
PRODUCTION環境で動かしたい

発生している問題・エラーメッセージ

ローカル上では問題なく読み込まれていた/app/assets/配下の画像、CSS、jsが、
本番環境のプリコンパイルで、/public/配下に移ったら、うまく読み込まれなくなりました。
ブラウザで静的IPを叩けば、HTML構造は閲覧でき、
別途publicディレクトリの画像のURLを直で叩くとブラウザで閲覧できるので、
参照先の指定がうまくいっていないと考えています。

ChromeでHTMLのソースを確認したところ、下記のように記述されていました。

(前略)
<link rel="stylesheet" media="all" href="/stylesheets/application.css" data-turbolinks-track="true">
(中略)
<script src="/javascripts/application.js" data-turbolinks-track="true"></script>
(中略)
<img src="/images/logo.png" alt="Logo">
(後略)

chromeの検証ツールでエラーを確認したところ、下記のようなエラーが出ていました

GET http://**.**.**.***/stylesheets/application.css 404 (Not Found)
GET http://**.**.**.***/javascripts/application.js 404 (Not Found)
GET http://**.**.**.***/images/logo.png 404 (Not Found)

public/assets/配下はこれらのようにファイル種別ごとにディレクトリは切られておらず、
画像もcssもjsもすべて同階層にプリコンパイルされています。
また、ファイル名には全てfingerprintが付与されているため、
このようなソースではディレクトリ指定があっていたとしても、
読み込まれないのではと思っています。

該当のソースコード

application.html.erb

(前略)
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
(中略)
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
(中略)
<%= image_tag 'logo.png' %>
(後略)

production.rbの中身

Rails.application.configure do
  # Settings specified here will take precedence over those in config/application.rb.

  # Code is not reloaded between requests.
  config.cache_classes = true

  # Eager load code on boot. This eager loads most of Rails and
  # your application in memory, allowing both threaded web servers
  # and those relying on copy on write to perform better.
  # Rake tasks automatically ignore this option for performance.
  config.eager_load = true

  # Full error reports are disabled and caching is turned on.
  config.consider_all_requests_local       = false
  config.action_controller.perform_caching = true

  # Enable Rack::Cache to put a simple HTTP cache in front of your application
  # Add `rack-cache` to your Gemfile before enabling this.
  # For large-scale production use, consider using a caching reverse proxy like
  # NGINX, varnish or squid.
  # config.action_dispatch.rack_cache = true

  # 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?
  config.serve_static_files = true

  # Compress JavaScripts and CSS.
  config.assets.js_compressor = :uglifier
  config.assets.css_compressor = :sass

  # Do not fallback to assets pipeline if a precompiled asset is missed.
  config.assets.compile = true

  # Asset digests allow you to set far-future HTTP expiration dates on all assets,
  # yet still be able to expire them through the digest params.
  config.assets.digest = true

  # stackoverflowのQAを元に画像を表示させるために追記してみる
  config.assets.enabled = true

  # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb

  # Specifies the header that your server uses for sending files.
  # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
  # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX

  # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
  # config.force_ssl = true

  # Use the lowest log level to ensure availability of diagnostic information
  # when problems arise.
  config.log_level = :debug

  # Prepend all log lines with the following tags.
  # config.log_tags = [ :subdomain, :uuid ]

  # Use a different logger for distributed setups.
  # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)

  # Use a different cache store in production.
  # config.cache_store = :mem_cache_store

  # Enable serving of images, stylesheets, and JavaScripts from an asset server.
  # config.action_controller.asset_host = 'http://assets.example.com'

  # Ignore bad email addresses and do not raise email delivery errors.
  # Set this to true and configure the email server for immediate delivery to raise delivery errors.
  # config.action_mailer.raise_delivery_errors = false

  # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
  # the I18n.default_locale when a translation cannot be found).
  config.i18n.fallbacks = true

  # Send deprecation notices to registered listeners.
  config.active_support.deprecation = :notify

  # Use default logging formatter so that PID and timestamp are not suppressed.
  config.log_formatter = ::Logger::Formatter.new

  # Do not dump schema after migrations.
  config.active_record.dump_schema_after_migration = false


end

試したこと

●試したこと1
Rails Asset Pipelineがうまくいかないときの問題の切り分けかた
を参考に、
「4−■URL例」までは確認しました
・publicディレクトリに画像がプリコンパイルされている
・publicディレクトリの画像のURLを直で叩くとブラウザで閲覧可能
「4-■Webサーバ設定例」については、
/usr/local/nginx-1.6.0/conf/conf.d/test_app.metheglin.jp.conf
が、自分の環境でいうとどこのファイルに当たるのかがわからず、確認できていません。

●試したこと2
teratailの「image_tagで画像が表示されません」という質問を参考に、
パスを「../画像名」としてみましたが、画像は表示されないままでした。

●試したこと3
(原理をきちんと理解できていないので関係ないかもしれませんが)
何かしらの理由で、環境の初期設定がうまくいっておらず、
production環境認定されていないのかもしれないと考え、
rails 初期設定メモを参考に、

export RAILS_SERVE_STATIC_FILES=true

を実行したり、
railsの3つの環境 & 環境の切り替えを参考に、

export RAILS_ENV=production

を実行したりしてみましたが、変化ありませんでした。

●プリコンパイルする際に使用しているコマンド

bundle exec rake assets:clobber RAILS_ENV=production
bundle exec rake assets:precompile RAILS_ENV=production
ps -ef | grep unicorn | grep -v grep
sudo nginx -s reload

一旦、public/assetsディレクトリを消してからプリコンパイルし、
unicorn再起動 → nginx再起動(これは必要かよくわからないので念のため実施しています)

原因や対策について、心当たりのある方がいらっしゃいましたら、
教えていただけないでしょうか。

よろしくお願いいたします。

補足情報

AWS EC2
ruby 2.3.1
Rails 4.2.6
unicorn v5.4.0
nginx/1.12.1

※以前、別のQAサイトで投稿した内容と同一内容ですが、
そちらでは回答がつかなかったため、こちらに投稿させていただきました。
情報は一部追加更新しております。
現在、そちらのサイトは退会し、こちらのサイトに一本化しました。
退会したサイトは回答がつかなかったことによる削除はできないため、残ってしまっています。

1

1 件の回答 1

0

下記の手順で解決しました。
(紆余曲折していますが、実際に追ったステップを書きます)

■原因
unicorn再起動のコマンドが間違っていたため、再起動できていなかった

■対応手順
1.PIDの確認
ps -ef | grep unicorn | grep -v grep

2.unicornの停止
kill [PID]

3.unicornが停止していることを確認
ps -ef | grep unicorn | grep -v grep

4.すでに生成されたプリコンパイルファイルの削除
bundle exec rake assets:clobber RAILS_ENV=production

5.プリコンパイルの実行
rake assets:precompile RAILS_ENV=production

6.unicornの再起動
unicorn_rails -c /var/www/rails/App_name/config/unicorn.conf.rb -D -E production

7.再起動していることを確認
ps -ef | grep unicorn | grep -v grep

8.nginxの再起動
sudo nginx -s reload

9.ブラウザで静的IPにアクセス
→ HTTP ERROR 500と表示される

10.log/nginx.error.log確認
→config/secrets.ymlのSECRET_KEY_BASEがうまくセットされていない旨が書かれていた

11.改めて、SECRET_KEY_BASEをセット
SECRET_KEY_BASE= 適宜記入
export SECRET_KEY_BASE
env | grep SECRET_KEY_BASE

12.1~8までを再度実行

13.ブラウザで静的IPにアクセス
→画像やcssが反映されていることを確認

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。