船木俊介「デジタル進化論」

スーパーソフトウエア東京オフィス代表&キッズラインCTO

AWS EC2サーバの構築 - Webサービス開発フロー(3)

前回からの続き

4.AWS EC2サーバの構築

サーバはruby,rails,MySQLの環境構築はもちろん、nginxをリバースプロキシとして使用するのでその設定を行います。

まずは新規にEC2を作っていきます。AWSの管理コーソールからEC2を選び、「Launch Instance」、サーバは「Amazon Linux AMI」「t2.micro」、セキュリティグループで「http TCP 80」を追加、新しいssh keyをダウンロードしておきます。

aw1

ダウンロードしたpem keyを使って、サーバにSSHで接続します。

$ chmod 600 ~/.ssh/blog_rwerck.pem
$ ssh -i ~/.ssh/blog_rwerck.pem ec2-user@xxx.xxx.xxx.xxx

       __|  __|_  )
       _|  (     /   Amazon Linux AMI
      ___|\___|___|

https://aws.amazon.com/amazon-linux-ami/2014.09-release-notes/
18 package(s) needed for security, out of 42 available
Run "sudo yum update" to apply all updates.

最初にyumアップデートしておきましょう。

$ sudo yum update

必要なライブラリをインストールします。

$ sudo yum install -y gcc-c++ patch readline readline-devel zlib zlib-devel libyaml-devel libffi-devel openssl-devel make bzip2 autoconf automake libtool bison git

 

rubyをインストール

ruby-buildとrbenvを使います。

$ cd
$ git clone git://github.com/sstephenson/ruby-build.git

Cloning into 'ruby-build'...
remote: Counting objects: 4186, done.
remote: Compressing objects: 100% (12/12), done.
remote: Total 4186 (delta 3), reused 0 (delta 0)
Receiving objects: 100% (4186/4186), 755.92 KiB | 252.00 KiB/s, done.
Resolving deltas: 100% (2130/2130), done.
Checking connectivity... done.

$ cd ruby-build
$ sudo ./install.sh
$ cd
$ git clone git://github.com/sstephenson/rbenv.git ~/.rbenv

Cloning into '/home/ec2-user/.rbenv'...
remote: Counting objects: 2002, done.
remote: Total 2002 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (2002/2002), 318.87 KiB | 153.00 KiB/s, done.
Resolving deltas: 100% (1249/1249), done.
Checking connectivity... done.

$ echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bash_profile
$ echo 'eval "$(rbenv init -)"' >> ~/.bash_profile
$ source ~/.bashrc
$ exec $SHELL -l
$ rbenv install -l
$ rbenv install 2.1.5;rbenv rehash

Downloading ruby-2.1.5.tar.gz...
-> http://dqw8nmjcqpjn7.cloudfront.net/4305cc6ceb094df55210d83548dcbeb5117d74eea25196a9b14fa268d354b100
Installing ruby-2.1.5...
Installed ruby-2.1.5 to /home/ec2-user/.rbenv/versions/2.1.5

$ rbenv global 2.1.5;rbenv rehash

バージョンを確認

$ ruby -v
ruby 2.1.5p273 (2014-11-13 revision 48405) [x86_64-linux]

 

bundlerをインストール

$ gem install bundler --no-rdoc --no-ri;rbenv rehash

Fetching: bundler-1.7.9.gem (100%)
Successfully installed bundler-1.7.9
1 gem installed

 

railsをアプリケーションに合わせたバージョン指定してインストール

$ gem install rails -v 4.1.4 --no-rdoc --no-ri
$ rbenv rehash
$ rails -v
Rails 4.1.4

 

sqlite3をインストール

$ sudo yum install sqlite-devel
$ gem install sqlite3;rbenv rehash

 

MySQLをインストール

$ sudo yum install mysql-server mysql-devel

/etc/my.cnfで文字コードをUTF-8に設定しておきます。[mysqld]にはcharacter-set-server=utf8、[mysql]と[client]にはdefault-character-set=utf8を追記します。

$ sudo vi /etc/my.cnf

/etc/my.cnf

[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
# Settings user and group are ignored when systemd is used.
# If you need to run mysqld under a different user or group,
# customize your systemd unit file for mysqld according to the
# instructions in http://fedoraproject.org/wiki/Systemd
character-set-server=utf8

[mysql]
default-character-set=utf8

[client]
default-character-set=utf8

[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

MySQLを起動して、ログインできるか確認。

$ sudo service mysqld start

Initializing MySQL database:  Installing MySQL system tables...
OK
Filling help tables...
OK

To start mysqld at boot time you have to copy
support-files/mysql.server to the right place for your system

PLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER !
To do so, start the server, then issue the following commands:

/usr/bin/mysqladmin -u root password 'new-password'
/usr/bin/mysqladmin -u root -h ip-172-31-13-193 password 'new-password'

Alternatively you can run:
/usr/bin/mysql_secure_installation

which will also give you the option of removing the test
databases and anonymous user created by default.  This is
strongly recommended for production servers.

See the manual for more instructions.

You can start the MySQL daemon with:
cd /usr ; /usr/bin/mysqld_safe &

You can test the MySQL daemon with mysql-test-run.pl
cd /usr/mysql-test ; perl mysql-test-run.pl

Please report any problems at http://bugs.mysql.com/

                                                           [  OK  ]
Starting mysqld:                                           [  OK  ]
$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.5.40 MySQL Community Server (GPL)

Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| test               |
+--------------------+
4 rows in set (0.00 sec)

後ほどプロダクション環境で使うデータベースを作成しておきます。

mysql> create database rweckersample_production;
Query OK, 1 row affected (0.03 sec)

 

node.jsをインストール

JavascriptランタイムがないとExecJSのエラーが出るので、予めnode.jsをインストールしておきます。curlのコマンド一発でnvmをインストール。

$ curl https://raw.githubusercontent.com/creationix/nvm/v0.22.0/install.sh | bash

 % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  5102  100  5102    0     0   3964      0  0:00:01  0:00:01 --:--:--  3964
=> Downloading nvm from git to '/home/ec2-user/.nvm'
=> Cloning into '/home/ec2-user/.nvm'...
remote: Counting objects: 2857, done.
remote: Compressing objects: 100% (9/9), done.
remote: Total 2857 (delta 4), reused 0 (delta 0)
Receiving objects: 100% (2857/2857), 542.28 KiB | 227.00 KiB/s, done.
Resolving deltas: 100% (1571/1571), done.
Checking connectivity... done.

=> Appending source string to /home/ec2-user/.bashrc
=> Close and reopen your terminal to start using nvm
$ source ~/.bashrc

nvmのls-remoteで最新版のバージョンを確認してインストールします。

$ nvm ls-remote
$ nvm install 0.11.14
######################################################################## 100.0%
Now using node v0.11.14
$ node -v
v0.11.14

 

nginxをインストール

Webサーバとして(リバースプロキシとして)nginxを使うので、インストールします。

$ sudo yum install nginx

nginxの起動確認

$ sudo /etc/init.d/nginx start
nginx を起動中:                                            [  OK  ]

ブラウザでpublicDNS(ec2-xxx-xxx-xxx-xxx.ap-northeast-1.compute.amazonaws.com)にアクセスするとnginxのwelcome画面が表示されることを確認。

aw2

$ sudo /etc/init.d/nginx stop
nginx を停止中:                                            [  OK  ]

 

Unicornとの連携設定を行っておく

railsアプリケーションをデプロイした際にはUnicornと連携するため、設定ファイルを作成しておきます。ec2-xxx-xxx-xxx-xxx.ap-northeast-1.compute.amazonaws.comの部分は、EC2のpublic DNSに合わせて変更してください。

/etc/nginx/conf.d/rwerck.conf

upstream ec2-xxx-xxx-xxx-xxx.ap-northeast-1.compute.amazonaws.com {
    server unix:/tmp/unicorn.sock;
}

server {
    listen       80;
    server_name  rwerckersample;
    root         /usr/share/nginx/html;

    location ~ ^/uploads/ {
        root    /home/ec2-user/rwerckersample/current/public;
        gzip_static on; # to serve pre-gzipped version
        expires 1y;
        add_header Cache-Control public;
        add_header ETag "";
        break;
    }

    location ~ ^/assets/ {
        root     /home/ec2-user/rwerckersample/current/public;
        gzip_static on; # to serve pre-gzipped version
        expires 1y;
        add_header Cache-Control public;
        add_header ETag "";
        break;
    }

    location / {
        proxy_pass http://ec2-xxx-xxx-xxx-xxx.ap-northeast-1.compute.amazonaws.com;
    }

    # redirect server error pages to the static page /40x.html
    #
    error_page  404              /404.html;
    location = /40x.html {
    }

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
    }
}
$ sudo /etc/init.d/nginx start
nginx を起動中:                                            [  OK  ]