LoginSignup
8
5

More than 5 years have passed since last update.

railsをproductionモードで起動する[Rails 5.1]

Last updated at Posted at 2018-04-28

docker + Railsの環境において、productionモードで起動した話
「ちげぇよ!」って話があれば教えてくださいー

[追記]
Railsのバージョンは5.1
5.2になると少し違った方法になる

内容

  • Railsをproductionモードで起動
  • 環境はdockerにRailsコンテナとmysqlコンテナが存在するパティーン

やったこと

secret_key_baseを設定

secret_key_baseを生成する

下記コマンドを実行

bash
rails secrets:setup

実行すると
- secrets.yml.key
- secrets.yml.enc
が生成される

secrets.yml.encを設定

secrets.yml.encを書き換える
下記コマンドを実行

bash
EDITOR=vim rails secrets:edit

EDITORで指定したエディタで開かれる(今回はvim)
※コンテナ内でvimが使用できない場合は、apt-getでインストール

bash
apt-get update
apt-get install vim

secret_key_baseの末尾に以下を記載

vim
production:
  secret_key_base: xxxxxxxxxxxxxxxxxxx

xxxx...は、「secrets.yml.key」に出力された値を記載すること

config/environments/production.rbに設定を追記

config/environments/production.rb
config.read_encrypted_secrets = true

assetsのプリコンパイル

railsの設定を追加

config/evnironments/production.rbに設定を追記
(場合によってはconfig/environments/production.rbの方が都合が良い場合もある)

config/evnironments/production.rb
config.serve_static_files = true
config.assets.js_compressor = :uglifier
config.assets.js_compressor = Uglifier.new(harmony: true)
config.assets.paths << config.root.join("node_modules")

yarnでadmin-lte(bootstrapのテンプレート)をnode_modules配下に配置してるので、
ブラウザからassetsを参照した際にnode_modules配下も参照するようにする

スタイルシートやapplication.scssに@importが存在する場合、
application.scssのrequireに変更する
※既存の@importは削除して良い

環境変数の設定

docker-compose.ymlの変更

dockerコンテナを使用しているため、
コンテナ内の環境変数を変更

docker-compose.yml
environment:
  RAILS_ENV: 'production'
  RACK_ENV: 'production'

unicornを使用してる場合は起動コマンドも同様に変更

docker-compose.yml
command: bundle exec unicorn -c config/unicorn.rb -E production -l 3000

いよいよコマンド実行

プリコンパイルを実行

RAKE
rake assets:precompile

public/assets配下にプリコンパイルされたファイルたちが生成される
プリコンパイルのタイミングは、
- 手動
- 初回接続時
- デプロイ時
の設定が可能(ここでは触れない)

コンテナ起動!

以上を設定すればコンテナがproductionモードで起動する(はず)
productionモードであることを確認するには、
ブラウザからRoutingErrorを発生させた時に、
ルーティング一覧が表示されなければOK(「管理者はログを見てね」みたいなやつが表示される)

最後に

結構ハマったけど、なんだかんだできた
データベースはdatabese.ymlの設定を変えてあげれば
接続先やテーブル名の変更が可能

参考にさせていただいた記事様

Rails 5.1のencrypted secretsの運用について考える

ありがとうございました。

8
5
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
8
5