ror配置unicorn部署

unicorn是目前在ror上比较流行的应用服务器,配合nginx用来直接部署rails程序,下面这种方式应该是共享socket,不断fork子进程,有点类似php-fpm的模式

 

安装unicorn

gem install unicorn
或者在你的项目里修改gemfile
gem 'unicorn'

 

流程描述

给rails程序配置unicorn的启动脚本
在外部unicorn_rails /xxxx/yyyy/zzzz/unicorn.rb启动rails程序
nginx配置下,连接到后端的ror程序

 

下面是详细的脚本部分

比如我们有个名字为hello的ror项目

在hello/config下建立unicorn.rb

root_path = File.expand_path '../', File.dirname(__FILE__)

log_file = root_path + '/log/unicorn.log'
err_log  = root_path + '/log/unicorn_error.log'

pid_file = '/tmp/unicorn_hello.pid'
old_pid = pid_file + '.oldbin'

socket_file = '/tmp/unicorn_hello.sock'

worker_processes 6
working_directory root_path
listen socket_file, backlog: 1024
timeout 30

pid pid_file
stderr_path err_log
stdout_path log_file

preload_app true

before_exec do |server|
  ENV['BUNDLE_GEMFILE'] = root_path + '/Gemfile'

  defined?(ActiveRecord::Base) and
      ActiveRecord::Base.connection.disconnect!
end

before_fork do |server, worker|
  if File.exists?(old_pid) && server.pid != old_pid
    begin
      Process.kill('QUIT', File.read(old_pid).to_i)
    rescue Errno::ENOENT, Errno::ESRCH
      puts "Send 'QUIT' signal to unicorn error!"
    end
  end

  defined?(ActiveRecord::Base) and
      ActiveRecord::Base.establish_connection
end

 

在hello项目的外面,建立start_hello.sh

#!/bin/sh

UNICORN=unicorn_rails
#这里需要全路径
CONFIG_FILE=/home/mmc/Projects/ruby/hello/config/unicorn.rb
 
case "$1" in
  start)
  #$UNICORN -c $CONFIG_FILE -E production -D
  $UNICORN -c $CONFIG_FILE -D
  ;;
  stop)
  kill -QUIT `cat /tmp/unicorn_hello.pid`
  ;;
  restart|force-reload)
    kill -USR2 `cat /tmp/unicorn_hello.pid`
  ;;
  *)
   echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
   exit 3
   ;;
esac

执行sh start_hello.sh start

 

最后配置nginx

upstream unicorn {
    server unix:/tmp/unicorn_hello.sock fail_timeout=0;
}
 
server {
  listen 80 default deferred;
  root /home/mmc/Projects/ruby/hello/;
  
 
  location ^~ /assets/ {
    gzip_static on;
    expires max;
    add_header Cache-Control public;
  }
 
  try_files $uri/index.html $uri @unicorn;
  location @unicorn {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_pass http://unicorn;
  }
 
  error_page 500 502 503 504 /500.html;
  client_max_body_size 4G;
  keepalive_timeout 10;
}

启动sudo invoke-rc.d nginx restart

 

http://127.0.0.1应该能看到ror的页面了

posted @ 2014-12-10 15:56  自由出土文物  阅读(296)  评论(0编辑  收藏  举报