質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Ruby on Rails 6

Ruby on Rails 6は、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Docker

Dockerは、Docker社が開発したオープンソースのコンテナー管理ソフトウェアの1つです

Q&A

解決済

2回答

5039閲覧

Rails6のproductionモードで動かしたいが、画面が正常に表示されない。

yu-imu

総合スコア35

Ruby on Rails 6

Ruby on Rails 6は、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Docker

Dockerは、Docker社が開発したオープンソースのコンテナー管理ソフトウェアの1つです

0グッド

1クリップ

投稿2020/03/29 15:19

編集2020/03/31 00:22

前提・実現したいこと

Ruby on Rails5.1→6にupdateしたのですが、ローカルのPC上でproduction環境で動かした際に画面が真っ白な状態でエラーが何も発生しないため原因が特定できず困っております。

開発環境は、DockerにRailsの環境を立てています。また、dev環境では正常に動作するのでproduction環境の設定に何らかの原因があると思っております。正常にdocker buildは完了しておりますが、localhostを叩くと画面が真っ白でJSがレンダリングされていませんでした。

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

docker-compose upのログ

Puma starting in single mode... rails_1 | * Version 3.12.4 (ruby 2.6.5-p114), codename: Llamas in Pajamas rails_1 | * Min threads: 5, max threads: 5 rails_1 | * Environment: production rails_1 | * Listening on tcp://0.0.0.0:3000 rails_1 | * Listening on unix:///アプリ名/tmp/sockets/puma.sock rails_1 | Use Ctrl-C to stop nginx_1 | 192.168.160.1 - - [29/Mar/2020:14:22:43 +0000] "GET / HTTP/1.1" 200 2281 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36" "-" nginx_1 | 192.168.160.1 - - [29/Mar/2020:14:22:43 +0000] "GET /packs/ClinentSideRendering-8d5918d162f33d66fdca.js HTTP/1.1" 200 133 "https://localhost/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36" "-"

該当のソースコード

devとの差分は、★が付いている行のみです。

docker-compose.prod.yml

version: '3' services: db: build: ./db/ environment: MYSQL_DATABASE: アプリ名_production ★DB名が異なる MYSQL_USER: root MYSQL_ROOT_PASSWORD:XXX ports: - 3309:3306 volumes: - mysql-data:/var/lib/mysql rails: &app_base build: context: . volumes: - .:/アプリ名 - /アプリ名/node_modules - public-data:/アプリ名/public - tmp-data:/アプリ名/tmp - log-data:/アプリ名/log environment: RAILS_ENV: production ★devでは、developmentを設定 REDIS_URL: redis://redis:6379 RACK_ENV: production ★production 環境のみ設定 depends_on: - db - redis command: sh ./launch.sh tty: true stdin_open: true nginx: build: context: ./nginx ports: - 80:80 - 443:443 depends_on: - rails volumes: - public-data:/アプリ名/public - tmp-data:/アプリ名/tmp redis: image: redis:6.0-rc2-alpine ports: - 6379:6379 volumes: - ./data/redis:/data command: redis-server --appendonly yes volumes: public-data: tmp-data: log-data: mysql-data:

Rails6に設定後のbundle exec rails app:updateから何も変更を加えていません。

config/environments/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 # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). # config.require_master_key = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? # Compress CSS using a preprocessor. # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = 'http://assets.example.com' # 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 # Store uploaded files on the local file system (see config/storage.yml for options). config.active_storage.service = :local # Mount Action Cable outside main process or domain. # config.action_cable.mount_path = nil # config.action_cable.url = 'wss://example.com/cable' # config.action_cable.allowed_request_origins = [ 'http://example.com', /http://example.*/ ] # 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 = [ :request_id ] # Use a different cache store in production. # config.cache_store = :mem_cache_store # Use a real queuing backend for Active Job (and separate queues per environment). # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "jirorianntena_production" config.action_mailer.perform_caching = false # 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 # Use a different logger for distributed setups. # require 'syslog/logger' # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') if ENV["RAILS_LOG_TO_STDOUT"].present? logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) end # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false # Inserts middleware to perform automatic connection switching. # The `database_selector` hash is used to pass options to the DatabaseSelector # middleware. The `delay` is used to determine how long to wait after a write # to send a subsequent read to the primary. # # The `database_resolver` class is used by the middleware to determine which # database is appropriate to use based on the time delay. # # The `database_resolver_context` class is used by the middleware to set # timestamps for the last write to the primary. The resolver uses the context # class timestamps to determine how long to wait before reading from the # replica. # # By default Rails will store a last write timestamp in the session. The # DatabaseSelector middleware is designed as such you can define your own # strategy for connection switching and pass that into the middleware through # these configuration options. # config.active_record.database_selector = { delay: 2.seconds } # config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver # config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session end

launch.sh // Railsの起動コマンド(docker-compose.prod.ymlの29行目)

bundle exec rake db:migrate cp -rf /tmp/public/* /アプリ名/public/ mkdir -p tmp/sockets bundle exec puma -C config/puma.rb

試したこと

■他にproduction環境のために設定したこと

  • Dockerでcredentials editを行いmaster.keyを生成しました。(https://qiita.com/at-946/items/8630ddd411d1e6a651c6)
  • RUN bundle exec rails assets:precompile RAILS_ENV=$RAILS_ENVを行う。
  • config.public_file_server.enabled = trueを設定した。 // NGINX利用しているので不要?

参考
https://qiita.com/ham0215/items/c0f9a4a0897d805cf886#production

補足情報(FW/ツールのバージョンなど)

別途確認したいファイルがあればコメントよろしくお願いします。

Rails用Dockerfile

FROM ruby:2.6.5-alpine ENV PROJECT アプリ名 RUN mkdir -p $PROJECT WORKDIR $PROJECT RUN apk add git RUN apk add --update bash perl RUN apk add libxslt-dev libxml2-dev build-base RUN apk add mysql-client mysql-dev RUN apk add --no-cache file RUN apk add yarn --no-cache RUN apk add tzdata --no-cache RUN apk add vim COPY . ./ RUN gem install bundler:2.1.4 && bundle install --jobs=4 RUN yarn install VOLUME /$PROJECT # puma.sockを配置するディレクトリを作成 RUN mkdir -p tmp/sockets RUN mkdir -p /tmp/public && \ cp -rf /アプリ名/public/* /tmp/public # prod環境でassetコンパイルが追加で必要 ENV NODE_OPTIONS="--max-old-space-size=4096" RUN bundle exec rails assets:precompile RAILS_ENV=$RAILS_ENV

chromeのconsoleに表示されるエラー

Refused to execute script from (ファイル名)because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答2

0

後学のために、原因を記述します。

主に、precompileができていない事が原因でした。
各種ログ、Rails,Nginx,Dockerを読んでも原因が見当たらずかなり沼にハマりました。
ベストアンサーにもある通り、/public配下に/assetsと/packs(js用フォルダ)を確認をすると良いです。 

/assetsが生成されていない場合、bundle exec bin/rails assets:precompile
/packsが生成されていない場合、webpackerのコンパイル

を実行すればひとまずコンパイルが実行されファイルが生成されました。

投稿2020/04/06 00:25

yu-imu

総合スコア35

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

yu-imu

2020/04/11 02:09 編集

気を付けていただきたいのが、Dockerfileに記述したからprecompileされていると思わない方がよい点です。結果的に、Dockerfileの記述が間違っていました。
nyako

2021/07/26 13:26

横からすみません。同様のエラーが発生しているのですがrails apiにて開発されていましたか?
guest

0

ベストアンサー

production環境だとアセットのプリコンパイルが必要だと思います。

https://railsguides.jp/asset_pipeline.html#production%E7%92%B0%E5%A2%83%E3%81%AE%E5%A0%B4%E5%90%88
↑の4.1辺りを参考にしてみてください。

とりあえず動かしたい!場合は
environment/production.rbの
config.assets.compile = false ←を trueに変えてみてください!

投稿2020/03/30 01:45

ymneet

総合スコア154

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

yu-imu

2020/04/04 07:09 編集

RUN RAILS_ENV=$RAILS_ENV bundle exec bin/rails assets:precompileをしているのでprecompileできていると思っていたのですが、ファイルには、manifest.jsonのみ生成されておりproductionの設定が間違っていることがわかりました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問