EC2にRailsアプリをデプロイ④ ~EC2でRailsを起動させる設定~


はじめに

これは前回の記事の続きです。
今回はEC2でRailsアプリを起動させるための設定をしていきます。

よろしくお願いします。

ssh鍵をGitHubに登録

アプリケーションのコードをGitHubを使ってEC2サーバにクローンします。
しかしながらEc2サーバにアプリをクローンしようとすると、GitHubは誰のEc2インスタンスかわからないのでssh公開鍵をGitHubに登録し、それを認証として利用してクローンwp許可してくれるようになります。

それでは下記のコードでssh鍵のペアを作成し、GitHubにssh鍵を登録していきます。
EC2にログインした状態で実行します。

ターミナル
[ec2-user@ip-172-31-23-189 ~]$ ssh-keygen -t rsa -b 4096
Generating public/private rsa key pair.
Enter file in which to save the key (/home/ec2-user/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/ec2-user/.ssh/id_rsa.
Your public key has been saved in /home/ec2-user/.ssh/id_rsa.pub.
The key fingerprint is:
3a:8c:1d:d1:a9:22:c7:6e:6b:43:22:31:0f:ca:63:fa ec2-user@ip-172-31-23-189
The key's randomart image is:
+--[ RSA 4096]----+
|    +            |
| . . =           |
|  = . o .        |
| * o . o         |
|= *     S        |
|.* +     .       |
|  * +            |
| .E+ .           |
| .o              |
+-----------------+

次にcatコマンドで表示されたssh公開鍵の値をコピーします。
下記のコマンドを実行します。

ターミナル
[ec2-user@ip-172-31-23-189 ~]$ cat ~/.ssh/id_rsa.pub

すると公開鍵の情報が表示されるので全てコピーします。

ターミナル(例)
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDLwt......
# 表示された内容すべてをコピー

以下をクリックしてGitHubにアクセスしてください。
SSH鍵登録リンク

遷移先で「New SSH key」をクリックします。
先ほどコピーした公開鍵を貼り付けて「Add SSH key」をクリックして保存します。

登録が完了したら、下記のコマンドで確認します。

ターミナル
[ec2-user@ip-172-31-23-189 ~]$ ssh -T [email protected]
Hi <Githubユーザー名>! You've successfully authenticated, but GitHub does not provide shell access.

yesかnoの質問があればyesでenterキーを押します。

Unicornをインストール

次にアプリケーションサーバーの設定をします。

Unicornというアプリケーションサーバーを使います。

Gemfileのgroup :production do ~ endに下記を記述します。

Gemfile
group :production do
  gem 'unicorn', '5.4.1'
end

unicorn.rbを作成

configの配下にunicorn.rbを作成します。「config/unicorn.rb」に下記の記述をします。

config/unicorn.rb
#サーバ上でのアプリケーションコードが設置されているディレクトリを変数に入れておく
app_path = File.expand_path('../../', __FILE__)

#アプリケーションサーバの性能を決定する
worker_processes 1

#アプリケーションの設置されているディレクトリを指定
working_directory app_path

#Unicornの起動に必要なファイルの設置場所を指定
pid "#{app_path}/tmp/pids/unicorn.pid"

#ポート番号を指定
listen 3000

#エラーのログを記録するファイルを指定
stderr_path "#{app_path}/log/unicorn.stderr.log"

#通常のログを記録するファイルを指定
stdout_path "#{app_path}/log/unicorn.stdout.log"

#Railsアプリケーションの応答を待つ上限時間を設定
timeout 60

#以下は応用的な設定なので説明は割愛

preload_app true
GC.respond_to?(:copy_on_write_friendly=) && GC.copy_on_write_friendly = true

check_client_connection false

run_once = true

before_fork do |server, worker|
  defined?(ActiveRecord::Base) &&
    ActiveRecord::Base.connection.disconnect!

  if run_once
    run_once = false # prevent from firing again
  end

  old_pid = "#{server.config[:pid]}.oldbin"
  if File.exist?(old_pid) && server.pid != old_pid
    begin
      sig = (worker.nr + 1) >= server.worker_processes ? :QUIT : :TTOU
      Process.kill(sig, File.read(old_pid).to_i)
    rescue Errno::ENOENT, Errno::ESRCH => e
      logger.error e
    end
  end
end

after_fork do |_server, _worker|
  defined?(ActiveRecord::Base) && ActiveRecord::Base.establish_connection
end

編集したらリモートリポジトリにコミット、プッシュします。
完了したら、EC2にローカルの全内容を反映させます。

下記のコマンドで権限を付与します。

ターミナル
#mkdirコマンドで新たにディレクトリを作成
[ec2-user@ip-172-31-23-189 ~]$ sudo mkdir /var/www/

#作成したwwwディレクトリの権限をec2-userに変更
[ec2-user@ip-172-31-23-189 ~]$ sudo chown ec2-user /var/www/

次にリポジトリURLをGitHubから取得してクローンします。
デプロイするGitHubのページにいって緑色の「Code」というボタンをクリックしてURLをコピーします。
下記のコマンドでクローンします。

ターミナル
[ec2-user@ip-172-31-23-189 ~]$ cd /var/www/
[ec2-user@ip-172-31-23-189 www]$ git clone コピーしたURLを貼り付ける

次回は本番環境での設定を行います。