149
151

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Posted at

Vagrant(CentOS6.5)にRuby2.1.2 Rails4.1をインストールの続き

Nginxインストール

今回はyumから
$ sudo yum install -y nginx

MySQLインストール

同じyumから
$ sudo yum install -y mysql mysql-server mysql-devel

ついでにデフォルトで立ち上げる設定に

$ sudo chkconfig --level 35 nginx on
$ sudo chkconfig --level 35 mysqld on

RailsInstalll

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

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

RailsInstall
$ rails new myApp --database=mysql

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

$ vim 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をインストール
$ bundle install --path vendor/bundle

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

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

Database作成
$ rake db:create

Unicorn設定

unicorn設定
$ vim conifg/unicorn.rb

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ファイルは使用しないので、逃がす
$ sudo mv /etc/nginx/conf.d/default.conf ~

Rails用のconfファイルを編集

$ sudo vim /etc/nginx/conf.d/myapp.conf

/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再起動
$ sudo /etc/init.d/nginx restart

Routing

テスト用にController作成
$ rails g controller Roots index

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

$ vim conifg/routes.rb

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起動

$ bundle exec unicorn_rails -c config/unicorn.rb -E development -D

この画面が出て来れば成功。

その他

unicornの停止

下記のコマンドで終了する事ができます。
$ cat /tmp/unicorn.pid | xargs kill

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

エラーが出る場合

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

参考

Unicorn fails to start on Vagrant box due to Errno::EPERM
Setting up Unicorn with Nginx
Configuring Nginx and Unicorn

149
151
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
149
151

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?