LoginSignup
0
1

More than 3 years have passed since last update.

EC2サーバーにRails + Nginx

Last updated at Posted at 2021-02-27

はじめに

すでにEC2へRailsを導入し、アプリをデプロイした状態(アプリケーションサーバー構築済)からNginxを導入します。
以下にその手順を記載してます。
EC2にRails + MySQL環境構築

Nginx導入

Nginx1というバージョンを導入。
EC2サーバー上で以下のコマンド。

$ sudo amazon-linux-extras install nginx1

Nginxの設定ファイルを編集

$ sudo vim /etc/nginx/conf.d/rails.conf

以下のように編集します。
<アプリケーション名><Elastic IP>は書き換えてください。

rails.conf
upstream app_server {
  # Unicornと連携させるための設定。アプリケーション名を自身のアプリ名に書き換えることに注意。
  server unix:/var/www/<アプリケーション名>/tmp/sockets/unicorn.sock;
}

# {}で囲った部分をブロックと呼ぶ。サーバの設定ができる
server {
  # このプログラムが接続を受け付けるポート番号
  listen 80;
  # 接続を受け付けるリクエストURL ここに書いていないURLではアクセスできない
  server_name <Elastic IP>;

  # クライアントからアップロードされてくるファイルの容量の上限を2ギガに設定。デフォルトは1メガなので大きめにしておく
  client_max_body_size 2g;

# 接続が来た際のrootディレクトリ
  root /var/www/<アプリケーション名>/public;

# assetsファイル(CSSやJavaScriptのファイルなど)にアクセスが来た際に適用される設定
  location ^~ /assets/ {
    gzip_static on;
    expires max;
    add_header Cache-Control public;
  }

  try_files $uri/index.html $uri @unicorn;

  location @unicorn {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_pass http://app_server;
  }

  error_page 500 502 503 504 /500.html;
}

nginxの権限を変更

POSTメソッドでもエラーが出ないようにするために権限変更。

$ cd /var/lib
$ sudo chmod -R 775 nginx

Nginxを起動して、設定ファイルを再読み込み

$ cd ~
$ sudo systemctl start nginx
$ sudo systemctl reload nginx

unicorn.rbを修正

Nginxを介した処理を行うためにunicornの設定を修正します。

unicorn.rb
listen 3000

↓以下のように修正

listen "#{app_path}/tmp/sockets/unicorn.sock"

ローカルで編集したファイルをリモートへpushします。
次にサーバー側にクローンします。

$ cd /var/www/<アプリ名(任意)>
$ git pull origin master

Unicornを再起動

Unicornのプロセスをkillして、再起動する作業を行います。

$ ps aux | grep unicorn
$ kill <確認したunicorn rails masterのPID>

Unicornを起動します。

$ RAILS_SERVE_STATIC_FILES=1 unicorn_rails -c config/unicorn.rb -E production -D

ブラウザで確認

ブラウザからElastic IPでアクセスすると、アプリケーションにアクセスできます(:3000をつける必要なし)。なお、この時もunicornが起動している必要があります。

エラーが出る場合は、nginxのlogの確認が必要です。

$ less /var/log/nginx/error.log

または、

$ less /var/www/<レポジトリ名>/log/unicorn.stderr.log

で、ログを確認します。

これで、EC2インスタンスにWEBサーバーとアプリケーションサーバーを構築できました。

0
1
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
0
1