メモ > 技術 > プログラミング言語: Ruby > Ruby on RailsをEC2へ導入
■Ruby on RailsをEC2へ導入
(下準備編)世界一丁寧なAWS解説。EC2を利用して、RailsアプリをAWSにあげるまで - Qiita
https://qiita.com/naoki_mochizuki/items/f795fe3e661a3349a7ce
RailsアプリをAWSにイチからデプロイするまでの手順メモ - Code of Duty
https://www.codeofduty.me/2018/01/31/railsapp-aws-deploy/
初心者向け:AWS(EC2)にRailsのWebアプリをデプロイする方法 目次 - Qiita
https://qiita.com/iwaseasahi/items/d5f2ef3eac5e349a8f7d
■サーバの基本的な設定
Amazon Linux 2 に Ruby on Rails を導入するものとする(VagrantのCentOS7でも同様に導入できた)
EC2起動後、サーバメモの Basis.txt をもとにしてサーバの基本的な設定を行う
また、セキュリティグループで3000番ポートを空けておく(Railsがデフォルトで使用するポート)
■依存ライブラリをインストール
Ruby On RailsをAmazonLinux2にインストール(2018.3) - Qiita
https://qiita.com/2gt/items/b8fba865a9059aacc61e
# yum -y install git
# yum -y install gcc
# yum -y install openssl-devel
# yum -y install readline-devel
# yum -y install zlib-devel
# yum -y install sqlite-devel
# curl --silent --location https://rpm.nodesource.com/setup_10.x | sudo bash -
# yum -y install nodejs
# npm -v
# node -v
■Ruby(rbenv)をインストール
Amazon Linux 2にrbenvをいれる - Qiita
https://qiita.com/ryooob/items/ce3354c9f2e0f202ff89
rbenv で ruby の環境を整える - Qiita
https://qiita.com/ringo/items/4351c6aee70ed6f346c8
※Rubyを使いたいユーザになっておく
どのユーザからもRubyを使用できるようにする場合、「どのユーザからもRubyを使用できるようにする」を参照
※ここでは ec2-user でインストールを行うものとする
$ git clone https://github.com/sstephenson/rbenv.git ~/.rbenv
$ git clone https://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build
$ echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bash_profile
$ echo 'eval "$(rbenv init -)"' >> ~/.bash_profile
$ source ~/.bash_profile
$ rbenv --version
rbenv 1.1.2-4-g577f046
$ rbenv install --list
Available versions:
1.8.5-p52
1.8.5-p113
1.8.5-p114
〜中略〜
truffleruby-19.1.0
truffleruby-19.2.0
truffleruby-19.2.0.1
$ rbenv install 2.5.7 … 今回は Ruby 2.5.7 を使用する
$ rbenv global 2.5.7
$ rbenv rehash
$ which ruby
~/.rbenv/shims/ruby
$ ruby --version
ruby 2.5.7p206 (2019-10-01 revision 67816) [x86_64-linux]
■BundlerとSQLiteをインストール
$ gem install bundler sqlite3
■Railsをインストール
$ gem install rails -v 5.2.2 … 今回は Rails 5.2.2 を使用する。バージョンを省略すると最新版がインストールされる
$ rails --version
■Railsの動作確認(SQLite3)
※/var/www/プロジェクト名
の場所にインストールすべきか
# mkdir -p /var/www/rails-test … root権限でプロジェクト用ディレクトリを作成(存在しない場合)
# chown ec2-user. /var/www/rails-test
# chmod 775 /var/www/rails-test
$ cd /var/www … ec2-userでプロジェクトを作成
$ rails new rails-test --skip-bundle
$ cd rails-test
$ bundle install
$ rails g scaffold user name:string email:string
$ rake db:migrate
$ rails s -b 0.0.0.0
ブラウザから以下にアクセスする(サーバのIPアドレスが 13.231.145.182 の場合)
http://13.231.145.182:3000/
http://13.231.145.182:3000/users
ユーザ情報の登録と表示ができれば完了
Ruby - bundle install時に--skip-bundleをつけるメリット|teratail
https://teratail.com/questions/17323
■Bundler経由での動作確認
$ bundle exec rails s -b 0.0.0.0
「bundle exec」が無くても実質同じ結果を得られるようだが、環境依存のリスクを軽減できるらしい
ひとまずサーバ上では、Railsのコマンドは「bundle exec」を付けて実行しておくのが無難そう
Bundlerとは? - Qiita
https://qiita.com/io_fleming/items/14626a9cff44bc87e7db
bundle exec を理解したい。 - Qiita
https://qiita.com/nishisuke/items/79acacc9e7e7d519ee3f
Ruby on Rails - bundle exec と bin/rails の違い|teratail
https://teratail.com/questions/120475
■データベースにMySQLを使用する
MySQL(MariaDB)サーバをインストール
# yum -y install mariadb-server … root権限でインストール
# mysql --version
mysql Ver 15.1 Distrib 5.5.64-MariaDB, for Linux (x86_64) using readline 5.1
# systemctl start mariadb
# systemctl enable mariadb
クライアントコマンドもインストール
# yum -y install mysql-devel
サーバメモの Web.txt をもとにして、MySQLの基本的な設定を行う
今回は「webmaster / gV0+8k6BM#z7」の情報で「development」データベースを扱えるようにした
# mkdir /var/www/rails-mysql … root権限でプロジェクト用ディレクトリを作成
# chown ec2-user. /var/www/rails-mysql
# chmod 775 /var/www/rails-mysql
$ cd /var/www … ec2-userでプロジェクトを作成
$ rails new rails-mysql -d mysql --skip-bundle
$ cd rails-mysql
$ vi config/database.yml
ブラウザから以下にアクセスする
http://13.231.145.182:3000/
http://13.231.145.182:3000/users
ユーザ情報の登録と表示ができれば完了
■Unicornをインストールする
なぜrailsの本番環境ではUnicorn,Nginxを使うのか? ~ Rack,Unicorn,Nginxの連携について ~【Ruby On Railsでwebサービス運営】 - Qiita
https://qiita.com/takahiro1127/items/fcb81753eaf381b4b33c
nginx+Unicorn経由でアクセスすることにより、大量のアクセスを捌くための仕組みが利用できる
「rails s」での起動は、開発用のものと考えておく
また、コンソールから「bundle exec rails s -b 0.0.0.0」としなくても起動できる
username: root
password:
↓
username: webmaster
password: gV0+8k6BM#z7
development:
<<: *default
database: rails-mysql_development
↓
development:
<<: *default
database: development
$ bundle install
$ rails g scaffold user name:string email:string
$ rake db:migrate
$ bundle exec rails s -b 0.0.0.0
$ vi Gemfile … 単に「gem install unicorn」とするとunicornを起動できなかった
■nginxをインストールする
# Unicorn
gem 'unicorn' … ファイルの最後に追加★実際は本番と検収にのみインストールするか
$ gem install bundler
$ bundle install
$ vi config/unicorn.conf.rb
# set lets
$worker = 2
$timeout = 30
$app_dir = "/var/www/rails-mysql" … アプリケーションの場所を設定
$listen = File.expand_path 'tmp/sockets/.unicorn.sock', $app_dir
$pid = File.expand_path 'tmp/pids/unicorn.pid', $app_dir
$std_log = File.expand_path 'log/unicorn.log', $app_dir
# set config
worker_processes $worker
working_directory $app_dir
stderr_path $std_log
stdout_path $std_log
timeout $timeout
listen $listen
pid $pid
# loading booster
preload_app true
# before starting processes
before_fork do |server, worker|
defined?(ActiveRecord::Base) and ActiveRecord::Base.connection.disconnect!
old_pid = "#{server.config[:pid]}.oldbin"
if old_pid != server.pid
begin
Process.kill "QUIT", File.read(old_pid).to_i
rescue Errno::ENOENT, Errno::ESRCH
end
end
end
# after finishing processes
after_fork do |server, worker|
defined?(ActiveRecord::Base) and ActiveRecord::Base.establish_connection
end
# amazon-linux-extras list … root権限でインストール
# amazon-linux-extras install nginx1.12 -y
# systemctl start nginx
# systemctl enable nginx
# chmod -R 775 /var/lib/nginx … 設定しておかないと、postメソッドでエラーになるらしい
以下にアクセスして動作を確認する
http://13.231.145.182/
■nginx+Unicorn経由でアクセスする
# vi /etc/nginx/conf.d/rails-mysql.conf … root権限で設定。アプリケーション名をファイル名にしておく
以下にアクセスして動作を確認する
http://13.231.145.182/
http://13.231.145.182/users
問題なければ完了
なお、アクセスログやエラーログは、特に変更しなければ通常どおり以下の場所に保存される
/var/log/nginx
以下は構築の補足など
■どのユーザからもRubyを使用できるようにする
root 権限で /usr/local/rbenv などにインストールし、gem を使いたい場合は root 権限で行う(未検証)
ただしその場合、secure_path の設定なども必要となるみたい
CentOS7 全体でユーザ共通に使える rbenv をインストールする - らくがきちょう
http://sig9.hatenablog.com/entry/2016/10/04/120000
rbenvで入れたRubyを全ユーザが使えるようにする
https://cre8cre8.com/rails/rbenv-install-ruby-using-all-users.htm
■RubyやGemのコマンドを使おうとすると「command not found」「command exists in these Ruby versions」と表示される
使用するRubyのバージョンを特定できていない場合に起こる
「rbenv install 2.5.7」を実行した後、「rbenv global 2.5.7」のように指定しないとこのエラーになる
upstream unicorn_server {
server unix:/var/www/rails-mysql/tmp/sockets/.unicorn.sock … アプリケーションの場所をもとに設定
fail_timeout=0;
}
server {
listen 80;
client_max_body_size 4G;
server_name 13.231.145.182; … サーバのドメインもしくはIPアドレス
keepalive_timeout 5;
# Location of our static files
root /var/www/rails-mysql/public; … アプリケーションの場所をもとに設定
location ~ ^/assets/ {
root /var/www/rails-mysql/public; … アプリケーションの場所をもとに設定
}
location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
if (!-f $request_filename) {
proxy_pass http://unicorn_server;
break;
}
}
error_page 500 502 503 504 /500.html;
location = /500.html {
root /var/www/rails-mysql/public; … アプリケーションの場所をもとに設定
}
}
# systemctl restart nginx
$ cd /var/www/rails-mysql … プロジェクトの場所で Unicorn を起動
$ bundle exec unicorn_rails -c /var/www/rails-mysql/config/unicorn.conf.rb -D -E development
$ ps -ef | grep unicorn | grep -v grep
$ ruby -v … エラーになる
rbenv: ruby: command not found
The `ruby' command exists in these Ruby versions:
2.5.7
$ gem -v … エラーになる
rbenv: gem: command not found
The `gem' command exists in these Ruby versions:
2.5.7
$ rbenv global 2.5.7 … Rubyのバージョンを指定
$ rbenv rehash
$ ruby -v … エラーにならない
ruby 2.5.7p206 (2019-10-01 revision 67816) [x86_64-linux]
$ gem -v … エラーにならない
2.7.6.2
rbenv: ruby: command not found The `ruby' command exists in these Ruby versions: - Qiita
https://qiita.com/Kaisyou/items/34ea9b5800434c1e09e6
■Railsのコマンドを使おうとすると「Could not find a JavaScript runtime」と表示される
$ rails g scaffold user name:string email:string
Traceback (most recent call last):
49: from bin/rails:4:in `<main>'
48: from /var/www/.rbenv/versions/2.5.7/lib/ruby/gems/2.5.0/gems/activesupport-5.2.3/lib/active_support/dependencies.rb:291:in `require'
〜中略〜
2: from /var/www/.rbenv/versions/2.5.7/lib/ruby/gems/2.5.0/gems/execjs-2.7.0/lib/execjs.rb:4:in `<top (required)>'
1: from /var/www/.rbenv/versions/2.5.7/lib/ruby/gems/2.5.0/gems/execjs-2.7.0/lib/execjs.rb:5:in `<module:ExecJS>'
/var/www/.rbenv/versions/2.5.7/lib/ruby/gems/2.5.0/gems/execjs-2.7.0/lib/execjs/runtimes.rb:58:in `autodetect': Could not find a JavaScript runtime. See https://github.com/rails/execjs for a list of available runtimes. (ExecJS::RuntimeUnavailable)
このように表示される場合、Node.js など何らかのExecJSランタイムをイントールする
【Rails】Could not find a JavaScript runtimeとなった時にやったこと - むぎちゃ
http://djandjan.hateblo.jp/entry/2018/07/25/224929
Amazon Linux2にnodejs+npmをインストールする方法 | SeleGee(セレジー)
https://selegee.com/develop/535/
■Railsにブラウザからアクセスしようとすると「サーバが見つかりません」になる
$ rails s
ではなく
$ rails s -b 0.0.0.0
で起動する
Rails 4.2 から rails server が Listen するアドレスが 0.0.0.0 から localhost に変わった
デフォルトの localhost では Public DNS 経由でアクセスできないので Listen するアドレスを変更する必要がある
環境によってはアクセスできるかもしれないが、EC2・Vagrant(CentOS)ともに「-b 0.0.0.0」の指定が必要だった
EC2でRailsアプリを起動したけどブラウザからアクセスできないとき - Qiita
https://qiita.com/sakaimo/items/dd138b39c7480fb2ebff
EC2 に Rails の開発環境をサクッと作る
https://blog.manabusakai.com/2015/06/rails-setup-on-ec2/
■RailsでMySQLを使う際に「bundle install」を実行するとエラーになる
以下のエラーになる
$ bundle install
〜中略〜
Fetching mysql2 0.5.2
Installing mysql2 0.5.2 with native extensions
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.
current directory: /var/www/.rbenv/versions/2.5.7/lib/ruby/gems/2.5.0/gems/mysql2-0.5.2/ext/mysql2
/var/www/.rbenv/versions/2.5.7/bin/ruby -r ./siteconf20191015-25857-1a191fl.rb extconf.rb --with-ldflags=-L/usr/local/opt/openssl/lib
--with-cppflags=-I/usr/local/opt/openssl/include
checking for rb_absint_size()... yes
checking for rb_absint_singlebit_p()... yes
checking for rb_wait_for_single_fd()... yes
checking for -lmysqlclient... no
-----
mysql client is missing. You may need to 'apt-get install libmysqlclient-dev' or 'yum install mysql-devel', and try again.
-----
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers. Check the mkmf.log file for more details. You may
need configuration options.
〜中略〜
An error occurred while installing mysql2 (0.5.2), and Bundler cannot continue.
Make sure that `gem install mysql2 -v '0.5.2' --source 'https://rubygems.org/'` succeeds before bundling.
エラーの案内どおり、「yum install mysql-devel」を実行してみる
root権限で実行
$ sudo su -
# yum install mysql-devel
# exit
再度以下を実行すると完了できた
$ bundle install
■Unicorn経由でRailsにアクセスすると「403 Forbidden」と表示される
Railsを /home/xxx 内に設置した場合、
以下のようにユーザディレクトリのパーミッションを変更する必要がある(700 を 701 に変更)
# chmod 701 /home/ec2-user
ただし、以下のように /var/www 内に設置すればこの問題は起こらないため、
特に理由がなければ /var/www 内に設置することを推奨
/var/www/プロジェクト名
unicorn nginx rails の連携で自分がハマったところ - Qiita
https://qiita.com/hatorijobs/items/8b57f9a89c3bfb442755
■Railsを削除する場合
# gem uninstall railties -v '6.0.0' … バージョンを指定して削除。この場合は 6.0.0 を削除している
■rackについて
なぜrailsの本番環境ではUnicorn,Nginxを使うのか? ~ Rack,Unicorn,Nginxの連携について ~【Ruby On Railsでwebサービス運営】 - Qiita
https://qiita.com/takahiro1127/items/fcb81753eaf381b4b33c
ApacheとNginxとPassengerとUnicornの違い【すごい初心者向け】 - ふじいけ技術メモ
http://fujiike.hateblo.jp/entry/2015/08/20/170751