RHEL7でRailsアプリのサーバを構築した【Railsアプリケーション・Unicorn のインストール・設定】

こちらは、

RHEL7でRailsアプリのサーバを構築した - takapiのブログ

Railsアプリケーション・Unicorn のインストール・設定 に関する記事です。

takapi86.hatenablog.com

Railsアプリケーションは完成している前提で進めます。

Railsアプリケーションをクローンする

github等からRailsアプリケーションをクローンします。

例:
$ git clone  --depth 1 https://github.com/takapi86/my-app.git

bundler のインストール

RubyのGem管理ツールである bundler をインストールします。

gem install bundler

Node.jsのインストール

必要に応じて設定します。 必須ではないので、Node.jsを使用しない場合はスキップします。

$ sudo yum remove -y nodejs npm # 最新のバージョンをインストールしたいので、すでにインストールされている場合は削除します。
$ sudo rpm -i https://rpm.nodesource.com/pub_6.x/el/7/x86_64/nodesource-release-el7-1.noarch.rpm
$ sudo yum -y install nodejs

sqliteのインストール

必要に応じて設定します。 必須ではないので、 sqlite を使用しない場合はスキップします。

$ sudo yum -y install sqlite
$ sudo yum -y install sqlite-devel

Railsアプリケーションのproduction設定

アセットのプリコンパイル

$ bundle exec rake assets:precompile RAILS_ENV=production

SECRET_KEY_BASEの設定

Railsでは config/secrets.yml にCookieのなりすまし対策のため、SECRET_KEY_BASE をCookie暗号化/復号化をしているようです。

production環境の場合、SECRET_KEY_BASE を環境変数に設定してあげる必要があります。

$ bundle exec rake secret
b1cb4a8933d20deaafb19e152217b7a53f784912ceb51dce6507e7336e671eef0136438d81604ca4c4c39cffc2ee93ba472b2d6cc597c0f4f3d39c05343dede1

動作確認のため、一時的にこの値を環境変数にセットします。

export SECRET_KEY_BASE=b1cb4a8933d20deaafb19e152217b7a53f784912ceb51dce6507e7336e671eef0136438d81604ca4c4c39cffc2ee93ba472b2d6cc597c0f4f3d39c05343dede1

各Gemのインストール

bunlde install しGemのインストールします。

$ cd ~/my-app/
$ bundle install

DB設定

$ vi config/database.yml
production:
  adapter: mysql2
  database: [DB名を入力します]
  pool: 5
  username: [DBのユーザを入力します]
  password: [DBのパスワードを入力します]
  host: localhost # 今回はDBサーバも同じサーバなので、localhostをしています。

DBマイグレーション

以下のコマンドで、アプリケーションのDB、テーブル、データを作成します。

RAILS_ENV=production bundle exec rake db:create
RAILS_ENV=production bundle exec rake db:migrate
RAILS_ENV=production bundle exec rake db:seed

Railsアプリケーションの動作確認

最終的に sustemdで起動・停止できるようにしますが、ひとまずunicornコマンドを実行し、 productionモードで起動できるか確認します。 unicornはデフォルトでは port8080 であがるので、8080宛にアクセスして動作確認を行います。

unicorn -E production

ここまで確認ができればRailsアプリケーション側の設定は完了です。

systemd の設定

設定したRailsアプリケーションをsystemdで起動・停止できるようにします。

config/unicorn.rb を編集

systemdからは unicornの設定ファイル config/unicorn.rb の内容で起動・停止できるようにします。

必要に応じて、以下に設定を追加・削除するとよいでしょう。

# config/unicorn.rb
app_path = '/home/ec2-user/my-app'
worker_processes 2
listen "#{app_path}/tmp/sockets/unicorn.sock", :backlog => 64
listen 8080, :tcp_nopush => true
pid "#{app_path}/tmp/pids/unicorn.pid"
rails_root = File.expand_path('../../', __FILE__)
ENV['BUNDLE_GEMFILE'] = rails_root + "/Gemfile"
stderr_path "#{app_path}/log/unicorn.stderr.log"
stdout_path "#{app_path}/log/unicorn.stdout.log"
before_exec do |server|
  ENV['BUNDLE_GEMFILE'] = "#{ENV['RAILS_ROOT']}Gemfile"
end

上記の設定でサーバがあがるかひとまず unicorn コマンドで確認してみます。

bundle exec unicorn -c config/unicorn.rb -E production

systemdの設定

/etc/systemd/system/unicorn.service

[Unit]
Description = unicorn Rack application server
Wants=mysqld.service
After=mysqld.service

[Service]
Environment=RAILS_ENV=production
Environment=SECRET_KEY_BASE=[SECRET_KEYを設定します。]
PIDFile=/home/ec2-user/my-app/tmp/pids/unicorn.pid
ExecStart=/home/ec2-user/.rbenv/shims/unicorn -c "/home/ec2-user/my-app/config/unicorn.rb" "/home/ec2-user/my-app/config.ru" -E production

[Install]
WantedBy = multi-user.target

自動起動の設定

$ sudo systemctl enable unicorn.service

以下のコマンドで登録できているか確認します。

$ sudo systemctl list-unit-files --type=service | grep unicorn
unicorn.service                               enabled

起動できるか確認します。

$ sudo systemctl start unicorn.service

NginxからUnicornを呼び出す

/etc/nginx/conf.d/ 以下のような設定ファイルを追加し、リバースプロキシできるようにします。 必要に応じて、以下に設定を追加・削除するとよいでしょう。

server {
  listen 80 default_server;
  server_name www.example.com;

  access_log /var/log/nginx/access.log;
  error_log /var/log/nginx/error.log;

  root /home/ec2-user/my-app/public;

  client_max_body_size 100m;
  error_page 404 /404.html;
  error_page 500 502 503 504 /500.html;
  try_files $uri/index.html $uri @unicorn;

  location @unicorn {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_pass http://localhost:8080;
  }
}

nginxを再起動します。

$ sudo systemctl restart nginx

ページにアクセスして確認する

ブラウザなどでサーバのURLへアクセスし、システムのページなどが表示されていればOKです。

表示されない場合は、ネットワーク周りやファイアウォールなどの設定を見直すとよいでしょう。

以上で、Railsアプリケーション・Unicorn のインストール・設定は完了です。