LoginSignup
63
62

More than 5 years have passed since last update.

Ruby2.0 + Rails4.0 + Passenger + Apache + MySQL + CentOS6.4 + Logwatch + 高速化設定 ( Webサーバー構築四苦八苦 4th Day, Ruby on Rails編 )

Last updated at Posted at 2013-11-15

前置き

結構サクサクインストール可能かと思います。
ところどころ手順通りいかないこともあるかと思いますが、
その際はエラー表示やログを見て下さい(^_^;
また、誤っている点などあればご指摘下さい!!

基本的に全部、sshでつないだリモート端末で行います
sshの設定などはこの記事で確認
また、ファイヤーウォールでアクセス制御を行いますので、こちらも要確認

とりあえず必要そうなものをごっそりインストール

$ sudo yum install -y zlib-devel perl-ExtUtils-MakeMaker httpd httpd-devel openssl-devel libyaml-devel libxml2-devel libxslt-devel libffi-devel readline-devel pcre-devel iconv-devel sqlite-devel mysql mysql-server mysql-devel curl-devel nkf

sqlite3のインストール

$ cd
$ wget http://www.sqlite.org/sqlite-autoconf-3071300.tar.gz
$ tar zxvf sqlite-autoconf-3071300.tar.gz 
$ cd sqlite-autoconf-3071300
$ ./configure
$ make
$ sudo make install
$ make clean

node.jsのインストール(javascript runtime用) ←これが結構大事

$ cd
$ wget http://nodejs.org/dist/v0.8.5/node-v0.8.5.tar.gz
$ tar zxvf node-v0.8.5.tar.gz
$ cd node-v0.8.5
$ ./configure
$ make
$ sudo make install
$ make clean

rbenvによるRubyのインストール

rbenvのインストール

$ cd
$ git clone git://github.com/sstephenson/rbenv.git .rbenv

$ echo 'export PATH="$HOME/.rbenv/bin/:$HOME/.rbenv:$PATH"'>>~/.bash_profile
$ echo 'eval "$(rbenv init -)"'>>~/.bash_profile

$ echo 'export PATH="$HOME/.rbenv/bin/:$HOME/.rbenv:$PATH"'>>~/.zshrc
$ echo 'eval "$(rbenv init -)"' >> ~/.zshrc  

$ exec $SHELL
$ mkdir -p ~/.rbenv/plugins
$ cd ~/.rbenv/plugins
$ git clone git://github.com/sstephenson/ruby-build.git

rubyのインストール

# rbenvでインストール可能なものが表示されるので、確認
$ rbenv install -l

# 今回はRuby2.0 の最新版 Ruby 2.0.0-p247 をインストール
$ rbenv install 2.0.0-p247
$ rbenv rehash

# 2.0.0-p247 をデフォルトの Ruby に設定。
$ rbenv global 2.0.0-p247

## 諸々確認
# rbenvのバージョン
$ rbenv versions
  system
* 2.0.0-p247 (set by ~/local/rbenv/version)

# Ruby コマンドの場所
$ which ruby
~/local/rbenv/shims/ruby

# 現在使用中のRuby のバージョン確認
$ ruby --version
ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-linux]

# gem のバージョンやインストール済みの gem を確認。
$ gem --version
$ gem list

bundler をインストール

$ rbenv exec gem install bundler
$ rbenv rehash

rails & 必要gemインストール

$ gem install rails --no-document
$ gem install rake 

passengerのインストール

$ gem install passenger
$ source ~/.zshrc もしくは bash_profile
$ passenger-install-apache2-module

すると以下の様な画面になる↓↓

Welcome to the Phusion Passenger Apache 2 module installer, v4.0.19.

This installer will guide you through the entire installation process. It
shouldn't take more than 3 minutes in total.

Here's what you can expect from the installation process:

 1. The Apache 2 module will be installed for you.
 2. You'll learn how to configure Apache.
 3. You'll learn how to deploy a Ruby on Rails application.

Don't worry if anything goes wrong. This installer will advise you on how to
solve any problems.

Press Enter to continue, or Ctrl-C to abort.

↑↑ここで Enter ↑↑
すると次の様な画面になる↓↓

--------------------------------------------
The Apache 2 module was successfully installed.

Please edit your Apache configuration file, and add these lines:

   LoadModule passenger_module /home/{hostname}/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/passenger-4.0.24/buildout/apache2/mod_passenger.so
   PassengerRoot /home/{hostname}/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/passenger-4.0.24
   PassengerDefaultRuby /home/{hostname}/.rbenv/versions/2.0.0-p247/bin/ruby

After you restart Apache, you are ready to deploy any number of Ruby on Rails
applications on Apache, without any further Ruby on Rails-specific
configuration!

Press ENTER to continue.

LoadModule passenger っというところのパラグラフをまるっとコピる。
同じくEnter
で次。

--------------------------------------------
Deploying a Ruby on Rails application: an example

Suppose you have a Rails application in /somewhere. Add a virtual host to your
Apache configuration file and set its DocumentRoot to /somewhere/public:

   <VirtualHost *:80>
      ServerName www.yourhost.com
      # !!! Be sure to point DocumentRoot to 'public'!
      DocumentRoot /somewhere/public    
      <Directory /somewhere/public>
         # This relaxes Apache security settings.
         AllowOverride all
         # MultiViews must be turned off.
         Options -MultiViews
      </Directory>
   </VirtualHost>

And that's it! You may also want to check the Users Guide for security and
optimization tips, troubleshooting and other useful information:

  /home/{hostname}/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/passenger-4.0.24/doc/Users guide Apache.html
  http://www.modrails.com/documentation/Users%20guide%20Apache.html

Enjoy Phusion Passenger, a product of Phusion (www.phusion.nl) :-)
https://www.phusionpassenger.com

Phusion Passenger is a trademark of Hongli Lai & Ninh Bui.

↑に出てきたVirtualhostのコードをコピります。

sudo vim /etc/httpd/conf.d/passenger.conf

はじめにコピーしておいた3行くらいの方のコードを以下のように貼り付けます。

VirtualHostの方は、後で使いますので、どこかにメモしておいて下さい。

/etc/httpd/conf.d/passenger.conf
        LoadModule passenger_module /home/{hostname}/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/passenger-4.0.24/buildout/apache2/mod_passenger.so
        PassengerRoot /home/{hostname}/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/passenger-4.0.24
        PassengerDefaultRuby /home/{hostname}/.rbenv/versions/2.0.0-p247/bin/ruby

この下に更に以下を追記。

/etc/httpd/conf.d/passenger.conf
# Passengerが追加するHTTPヘッダを削除するための設定(任意)。
Header always unset "X-Powered-By"
Header always unset "X-Rack-Cache"
Header always unset "X-Content-Digest"
Header always unset "X-Runtime"

# 必要に応じてPassengerのチューニングのための設定を追加(任意)。
# 詳しくはPhusion Passenger users guide(http://www.modrails.com/documentation/Users%20guide%20Apache.html)
PassengerMaxPoolSize 20
PassengerMaxInstancesPerApp 4
PassengerPoolIdleTime 3600
PassengerHighPerformance on
PassengerStatThrottleRate 10
PassengerSpawnMethod smart
RailsAppSpawnerIdleTime 86400
PassengerMaxPreloaderIdleTime 0

反映させる為にリスタートします

sudo service httpd start #またはrestart
sudo /sbin/chkconfig httpd on 

mysql

sudo service mysqld start #初回の初期化処理
sudo mysqladmin -u root password pass(=passは任意のpassword※あとで使う)
sudo /sbin/chkconfig mysqld on

railsの起動テスト( sqliteで )

$ cd
$ rails new app
$ cd app
$ rails g scaffold sample name:string
$ rake db:migrate
$ rails s

ブラウザにて、さくらから提供されたIPアドレスやURLに ":3000" を付けてアクセス

表示されたらOK
終了コマンドは + C

Forbiddenが出る場合

$ sudo chmod755/home/{username}

尚、このappはいらないので削除しておく

$ cd
$ rm -rf app

railsの起動テスト ( mysql )

mysql 設定

# db作成
$ mysql -u root -p
#password入力(先のmysqlで作った任意のpassword)

# mysqlに入りました
mysql> CREATE DATABASE app_01(任意の名前);
mysql> show databases; # 指定した名前のDBが出来たかどうか確認
mysql> exit;

app作成

$ cd
$ rails new app -d mysql
$ cd app
$ vim config/database.yml
-------

config/database.yml

development
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: app_development (←ここにさっき作ったDBの名前を入れる)
  pool: 5
  username: root
  password: #ここに先ほど設定したpassword記入
socket: /var/lib/mysql/mysql.sock
$ rails g scaffold sample name:string
$ rake db:migrate
$ rails s

ブラウザチェック

Forbiddenが出るなら読み取り権限があるかをチェック
ll -a を実行して、rがついているかどうか

$ sudo chmod755/home/{username}
#その他、読み取り権限があるかをチェック#ll -a を実行して、rがついているかどうか

Virtualhostの設定

sudo vim /etc/httpd/conf/httpd.conf
/etc/httpd/conf/httpd.conf

#最終行付近(コメント#を外す)
#NameVirtualHost *:80
->NameVirtualHost *:80

#以下を末尾に追記

先ほどメモっておいたVirutalHostの記載をココで使います。

<VirtualHost *:80>
        ServerName {IPアドレスなど}
        # !!! Be sure to point DocumentRoot to 'public'!
        DocumentRoot /home/{hostname}i/app/public
        RailsEnv development
        <Directory /home/{hostname}/app/public>
                # This relaxes Apache security settings.
                AllowOverride all
                # MultiViews must be turned off.
                Options -MultiViews
                Order allow,deny
                Allow from all
        </Directory>
</VirtualHost>

↑この辺の設定はこちらが参考になるかもしれません。
Apacheのログの表示形式を設定する方法 〜調べてみた編〜

反映させる為にリスタート

$ service httpd configtest
Syntax OK
$ sudo service httpd restart

ブラウザで http://{URL or IPアドレス}/samples にアクセスします。

むむ!?
アクセスすると↓のエラーがブラウザに表示されます

Could not find a JavaScript runtime. See https://github.com/sstephenson/execjs for a list of available runtimes. (ExecJS::RuntimeUnavailable)

なので一旦次のことをします。

Gemfileにtherubyracerを加えてインストール

$ vim Gemfile  
Gemfile
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
#gem 'therubyracer', platforms: :ruby
-> gem 'therubyracer', platforms: :ruby #コメントを外します
$ bundle install 

再度ブラウザで http://{URL or IPアドレス}/samples にアクセスします。
表示されたらOK

Gemfileに以下の記述があるとき、JavaScriptエンジンが必要になるので、node.jsを入れたのですが、うまくいかず、一旦rubyracerで対応しました。
こっちが正解なのかも?

gem 'coffee-script'

ログの監視

sudo yum install -y logwatch

設定はこちらから

$ vim /usr/share/logwatch/default.conf/logwatch.conf
----

#ログが保存されているディレクトリ
LogDir = /var/log
#メールの送信先
MailTo = username@hoge.com
#アーカイブされたログも含めるかどうか
Archives = Yes
#レポートの日付範囲を3つのオプションから。All, Today, Yesterday
Range = Yesterday
ログの詳細度、Low (=0), Med (=5), High (=10) または 0から10までの数字で
Detail = High
# チェックの対象となるサービスを /usr/share/logwatch/scripts/services/ 以下、あるいは All で指定。
Service = All
# メールコマンドパス
mailer = "sendmail -t"

その他はこちらから

mailの設定

$ sudo vim /etc/aliases
----

#最終行に以下を追加
root: sample@sample.com #メールアドレスを追加
$ sudo newaliases
$ echo test | mail root

エラーページの設定

/etc/httpd/conf/httpd.conf

Alias /error/ "/var/www/error/"

<IfModule mod_negotiation.c>
<IfModule mod_include.c>
    <Directory "/var/www/error">
        AllowOverride None
        Options IncludesNoExec
        AddOutputFilter Includes html
        AddHandler type-map var
        Order allow,deny
        Allow from all
        LanguagePriority en es de fr
        ForceLanguagePriority Prefer Fallback
    </Directory>

    ErrorDocument 404 /404.html
    ErrorDocument 500 /500.html
    ErrorDocument 502 /502.html
    ErrorDocument 503 /503.html
    ErrorDocument 504 /504.html

#    ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var
#    ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var
#    ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var
#    ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var
#    ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var
#    ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var
#    ErrorDocument 410 /error/HTTP_GONE.html.var
#    ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var
#    ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var
#    ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var
#    ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var
#    ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var
#    ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var
#    ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var
#    ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var
#    ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var
#    ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var

</IfModule>
</IfModule>

キャッシュ制御 / レスポンスヘッダ〜の追加 / Gzip圧縮

/etc/httpd/conf/httpd.conf

<VirtualHost *:80>
        ServerName {IPアドレスなど}
        # !!! Be sure to point DocumentRoot to 'public'!
        DocumentRoot /home/{hostname}/app/public/
        RailsEnv development
        <Directory /home/{hostname}/app/public/>
                # This relaxes Apache security settings.
                AllowOverride all
                # MultiViews must be turned off.
                Options -MultiViews
                Order allow,deny
                Allow from all
        </Directory>
        <Directory "/home/{hostname}/app/public/assets/">
        ExpiresActive On
        ExpiresDefault "access plus 1 year"
        Header set Cache-Control "public"
        Header unset ETag
        FileETag None
# Gzip圧縮
        AddEncoding x-gzip .gz
        Header set Vary Accept-Encoding
        RewriteEngine on
        RewriteCond %{HTTP:Accept-Encoding} \b(x-)?gzip\b
        RewriteCond %{REQUEST_FILENAME}.gz -f
        RewriteRule ^(.*)$ $1.gz [L]

# レスポンスヘッダ〜の追加
        Header set X-Frame-Options SAMEORIGIN
        Header set X-Content-Type-Options nosniff
        Header set X-XSS-Protection "1; mode-block"
        <FilesMatch \.css\.gz$>
          ForceType text/css
        </FilesMatch>

        <FilesMatch \.js\.gz$>
          ForceType text/javascript
        </FilesMatch>

    </Directory>
</VirtualHost>

最後にコードをGitHubに上げて管理する為の設定をします

こちらへ

ref)
http://easyramble.com/rbenv-on-rental-server.html
http://qiita.com/w7tree/items/027bcea3715ee0ba6050

63
62
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
63
62