Vagrant(CentOS6.5)にRails4.1 + Nginx + Unicorn + MySQL環境でRailsを起動する。



[Vagrant(CentOS6.5)にRuby2.1.2 Rails4.1をインストール](http://qiita.com/teitei_tk/items/27ae7b7e73791930929d)の続き

## Nginxインストール
今回はyumから
<code>$ sudo yum install -y nginx</code>

## MySQLインストール
同じyumから
<code>$ sudo yum install -y mysql mysql-server mysql-devel</code>


### ついでにデフォルトで立ち上げる設定に
```
$ sudo chkconfig --level 35 nginx on
$ sudo chkconfig --level 35 mysqld on
```


## RailsInstalll
インストールするディレクトリへ
<code>$ mkdir /path/to/dir/ && cd /path/to/dir/</code>

budnlerで管理したいので最初にインストール
<code>$ gem install bundle</code>

RailsInstall
<code>$ rails new myApp --database=mysql</code>

execjsのみでは動かないので、ランタイムも一緒にインストールする。
このタイミングでUnicornもインストール

<code>$ vim Gemfile</code>

```Gemfile
source 'https://rubygems.org'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.1.1'
# Use mysql as the database for Active Record
gem 'mysql2'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.3'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer',  platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0',          group: :doc

# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring',        group: :development

# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use unicorn as the app server
gem 'unicorn'

# use v8 engine
gem 'therubyracer'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

# Use debugger
# gem 'debugger', group: [:development, :test]
```

必要なgemをインストール
<code>$ bundle install --path vendor/bundle</code>

database.ymlに設定を追加
<code>$ vim conifg/database.yml</code>

```config/database.yml
default: &default
  adapter: mysql2
  encoding: utf8
  pool: 5
  username: hoge
  password: foobar
  socket: /var/lib/mysql/mysql.sock
```

Database作成
<code>$ rake db:create</code>


## Unicorn設定
unicorn設定
<code>$ vim conifg/unicorn.rb</code>

```conifg/unicorn.rb
@app_path = '/path/to/dir/myApp'

worker_processes 2
working_directory "#{@app_path}/"

# This loads the application in the master process before forking
# worker processes
# Read more about it here:
# http://unicorn.bogomips.org/Unicorn/Configurator.html
preload_app true

timeout 30

# This is where we specify the socket.
# We will point the upstream Nginx module to this socket later on
listen "/tmp/unicorn.sock", :backlog => 64

pid "/tmp/unicorn.pid"

# Set the path of the log files inside the log folder of the testapp
stderr_path "#{@app_path}/log/unicorn.stderr.log"
stdout_path "#{@app_path}/log/unicorn.stdout.log"

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
        sig = (worker.nr + 1) >= server.worker_processes ? :QUIT : :TTOU
        Process.kill(sig, File.read(old_pid).to_i)
      rescue Errno::ENOENT, Errno::ESRCH
      end
    end
 
    sleep 1
  end
 
after_fork do |server, worker|
  defined?(ActiveRecord::Base) and ActiveRecord::Base.establish_connection
end
```

## Nginx設定
デフォルトのconfファイルは使用しないので、逃がす
<code>$ sudo mv /etc/nginx/conf.d/default.conf ~</code>

Rails用のconfファイルを編集

<code>$ sudo vim /etc/nginx/conf.d/myapp.conf</code>

```/etc/nginx/conf.d/myapp.conf
upstream unicorn_server {
    # This is the socket we configured in unicorn.rb
    server unix:/tmp/unicorn.sock
    fail_timeout=0;
}

server {
	listen 80;
	client_max_body_size 4G;
	server_name _;

	keepalive_timeout 5;

	# Location of our static files
	root /path/to/dir/myApp/public;

	location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;

        # If you don't find the filename in the static files
        # Then request it from the unicorn server
        if (!-f $request_filename) {
            proxy_pass http://unicorn_server;
            break;
        }
	}

	error_page 500 502 503 504 /500.html;
	location = /500.html {
		root /path/to/dir/myApp/public;
	}
}
```

設定出来たら、Nginx再起動
<code>$ sudo /etc/init.d/nginx restart </code>


## Routing

テスト用にController作成
<code>$ rails g controller Roots index</code>

root(/)にアクセスした場合に、indexActionを見るようにする

<code>$ vim conifg/routes.rb</code>

```conifg/routes.rb
Rails.application.routes.draw do
  root :to => 'roots#index'

  # The priority is based upon order of creation: first created -> highest priority.
  # See how all your routes lay out with "rake routes".

  # You can have the root of your site routed with "root"
  # root 'welcome#index'

  # Example of regular route:
  #   get 'products/:id' => 'catalog#view'

  # Example of named route that can be invoked with purchase_url(id: product.id)
  #   get 'products/:id/purchase' => 'catalog#purchase', as: :purchase

  # Example resource route (maps HTTP verbs to controller actions automatically):
  #   resources :products

  # Example resource route with options:
  #   resources :products do
  #     member do
  #       get 'short'
  #       post 'toggle'
  #     end
  #
  #     collection do
  #       get 'sold'
  #     end
  #   end

  # Example resource route with sub-resources:
  #   resources :products do
  #     resources :comments, :sales
  #     resource :seller
  #   end

  # Example resource route with more complex sub-resources:
  #   resources :products do
  #     resources :comments
  #     resources :sales do
  #       get 'recent', on: :collection
  #     end
  #   end

  # Example resource route with concerns:
  #   concern :toggleable do
  #     post 'toggle'
  #   end
  #   resources :posts, concerns: :toggleable
  #   resources :photos, concerns: :toggleable

  # Example resource route within a namespace:
  #   namespace :admin do
  #     # Directs /admin/products/* to Admin::ProductsController
  #     # (app/controllers/admin/products_controller.rb)
  #     resources :products
  #   end
end
```

## unicorn起動
<code>$ bundle exec unicorn_rails -c config/unicorn.rb -E development -D</code>

この画面が出て来れば成功。
![](https://dl.dropboxusercontent.com/u/10402121/image/20140605_rails_setup.png)

## その他
### unicornの停止
下記のコマンドで終了する事ができます。
<code>$ cat /tmp/unicorn.pid | xargs kill</code>

もしくは全processごと強制終了
<code>$ ps ax | grep unicorn | awk '{print $1}' | xargs kill</code>


### エラーが出る場合
project以下の<code>log/unicorn*.log</code>に出力が吐かれているので、そこからエラー内容を確認


## 参考
[Unicorn fails to start on Vagrant box due to Errno::EPERM](http://stackoverflow.com/questions/16388342/unicorn-fails-to-start-on-vagrant-box-due-to-errnoeperm)
[Setting up Unicorn with Nginx](http://sirupsen.com/setting-up-unicorn-with-nginx/
)
[Configuring Nginx and Unicorn](http://sleekd.com/general/configuring-nginx-and-unicorn/)