はじめに
このGWはデータベースを使ったAPIを作成する勉強をしていた.検索するとlocalhostに環境を作ったりdocker-composeを使って環境を作ったりしている記事が多いが,今回はAWS EC2上にRails ServerとMariaDB Serverを立てることにした.ここにRuby on Railsの環境構築をしたログを残しておく.
以下EC2 Amazon Linux 2上にRuby環境を構築していく.簡単のためユーザーデータに以下のスクリプトを渡しておく.
#!/bin/bash
yum update -y
yum install -y git
Amazon Linux 2にはExtras Libraryというパッケージ群が存在していくつかのプログラミング言語の実行環境をインストールできる.しかしこれを使ってruby2.6をインストールするとruby 2.6の実行環境は作れるのだがRailsのインストールで詰まった.
$ sudo amazon-linux-extras install -y ruby2.6
$ ruby -v
ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-linux]
$ gem install -N rails -v 5.2.2
~~省略~~
ERROR: Error installing rails:
ERROR: Failed to build gem native extension.
current directory: /home/ec2-user/.gem/ruby/gems/nokogiri-1.10.9/ext/nokogiri
/usr/bin/ruby -I /usr/share/rubygems -r ./siteconf20200506-3653-17qqnkp.rb extconf.rb
mkmf.rb can't find header files for ruby at /usr/share/include/ruby.h
You might have to install separate package for the ruby development
environment, ruby-dev or ruby-devel for example.
extconf failed, exit code 1
$ sudo yum install -y ruby-devel rubygem-devel gcc
$ gem install -N rails -v 5.2.2
~~省略~~
*** 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.
nokogiri関連でエラーが出ていて色々調べたが結局Railsのインストールはできなかった.
rbenvを使ったインストール
そこでrbenvを通してRubyをインストールする.Qiitaの記事の通りにコマンドを叩くとRubyがインストールできる(最初はコンパイルができなくてインストールに失敗するのでopenssl-devel, readline-devel, zlib-develをインストールしてからrubyをインストールするようにする).
$ git clone https://github.com/sstephenson/rbenv.git ~/.rbenv
$ echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bash_profile
$ echo 'eval "$(rbenv init -)"' >> ~/.bash_profile
$ source .bash_profile
# rbenvがインストールできているか確認
$ rbenv -v
rbenv 1.1.2-30-gc879cb0
$ git clone git://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build
$ cd ~/.rbenv/plugins/ruby-build
$ sudo ./install.sh
# ruby2.7.0のインストールを試みる
$ rbenv install 2.7.0
~~省略~~
checking for gcc... no
checking for cc... no
checking for cl.exe... no
configure: error: in `/tmp/ruby-build.20200506122520.3754.5vaAE7/ruby-2.7.0':
configure: error: no acceptable C compiler found in $PATH
See `config.log' for more details
$ sudo yum install -y gcc
$ rbenv install 2.7.0
BUILD FAILED (Amazon Linux 2 using ruby-build 20200401-9-g3ef704e)
Inspect or clean up the working tree at /tmp/ruby-build.20200506122719.4083.RKzjEW
Results logged to /tmp/ruby-build.20200506122719.4083.log
$ less /tmp/ruby-build.20200506122719.4083.log
~~省略~~
*** Following extensions are not compiled:
-test-/cxxanyargs:
Could not be configured. It will not be installed.
/tmp/ruby-build.20200506122719.4083.RKzjEW/ruby-2.7.0/lib/mkmf.rb:471: The compiler failed to generate an executable file.
You have to install development tools first.
Check ext/-test-/cxxanyargs/mkmf.log for more details.
dbm:
Could not be configured. It will not be installed.
Check ext/dbm/mkmf.log for more details.
gdbm:
Could not be configured. It will not be installed.
Check ext/gdbm/mkmf.log for more details.
openssl:
Could not be configured. It will not be installed.
/tmp/ruby-build.20200506122719.4083.RKzjEW/ruby-2.7.0/ext/openssl/extconf.rb:97: OpenSSL library could not be found. You might want to use --with-openssl-dir=<dir> option to specify the prefix where OpenSSL is installed.
Check ext/openssl/mkmf.log for more details.
readline:
Could not be configured. It will not be installed.
/tmp/ruby-build.20200506122719.4083.RKzjEW/ruby-2.7.0/ext/readline/extconf.rb:62: Neither readline nor libedit was found
Check ext/readline/mkmf.log for more details.
zlib:
Could not be configured. It will not be installed.
Check ext/zlib/mkmf.log for more details.
~~省略~~
/tmp/ruby-build.20200506122719.4083.RKzjEW/ruby-2.7.0/lib/rubygems/core_ext/kernel_require.rb:92:in `require': cannot load such file -- openssl (LoadError)
$ sudo yum install -y openssl-devel readline-devel zlib-devel
# 必要なものをインストールしてからrubyのインストールをやり直す
$ rbenv install 2.7.0
$ $ rbenv global 2.7.0
$ ruby -v
ruby 2.7.0p0 (2019-12-25 revision 647ee6f091) [x86_64-linux]
ここまででRuby 2.7.0の実行環境ができた.
Amazon Linux 2のAMIから立ち上げたインスタンスにはMariaDBが標準でインストールされている.最初mysqlをインストールしようとしていたがうまくいかなかったのと,検証用の簡単なものなのでMariaDBを使うことにした(ちゃんとするならRDSを使えばいいはず).
こちらもQiitaの記事に従ってMariaDB Serverを立てる.
# インストール
$ sudo yum install -y mariadb-server
# 起動
$ sudo systemctl start mariadb
# 有効化
$ sudo systemctl enable mariadb
$ sudo systemctl is-enabled mariadb
# セキュリティ設定
$ sudo mysql_secure_installation
MariaDB Serverを立てたときremote accessを許可する必要がある.そこでMariaDBにログインしてから以下のコマンドを入力してVPC内部のRails Serverインスタンスからアクセスできるように設定する.
$ mysql -u root -p
MariaDB [(none)]> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%.compute.internal'
IDENTIFIED BY 'some_characters'
WITH GRANT OPTION;
MariaDB [(none)]> FLUSH PRIVILEGES;
APIモードでRailsをセットアップする.
$ sudo yum install -y mysql mysql-client mysql-devel
# railsのインストール
$ gem install -N rails -v 5.2.2
# APIを作成
$ rails new <api-name> --api -d mysql --skip-turbolinks --skip-test
# proxyのためnginxをインストールする.
$ sudo amazon-linux-extras install -y nginx1.12
$ sudo vi /etc/nginx/nginx.conf
$ sudo systemctl start nginx.service
$ rails s
nginxの設定はQiitaの記事を参考にする.
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
# Load dynamic modules. See /usr/share/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;
events {
worker_connections 1024;
}
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Load modular configuration files from the /etc/nginx/conf.d directory.
# See http://nginx.org/en/docs/ngx_core_module.html#include
# for more information.
include /etc/nginx/conf.d/*.conf;
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
- root /usr/share/nginx/html;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
location / {
+ proxy_pass http://localhost:3000;
+ proxy_http_version 1.1;
+ proxy_set_header Upgrade $http_upgrade;
+ proxy_set_header Connection 'upgrade';
+ proxy_set_header Host $host;
+ proxy_cache_bypass $http_upgrade;
}
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
}
この状態でRails ServerのパブリックIPにアクセスしてもMysql2::Error:ConnectionErrorが出ている.これはデータベースに接続できていないからなので設定を編集する.
/config/database.ymlのdefault部分のusername, password, hostを設定する.hostはMariaDB ServerのIPアドレスでusername, passwordはMariaDB Serverの用意のところで作成している.この状態でrails db:create
コマンドを使うとdevelopment, testのdatabaseが作成される.この後でrails s
コマンドでサーバーを起動してRails ServerのパブリックIPをブラウザで開くとRailsのページが表示されている.
おわりに
ここまででRails Serverが無事起動するようになっている.この後はモデルやコントローラを作成し,マイグレーションしてデータベースの初期データを渡してロジックを書いていけばAPIサーバーとして使えるようになる.