首页 > 代码库 > nginx + unicorn 部署rails项目

nginx + unicorn 部署rails项目

nginx + unicorn  部署 rails 项目,顾名思义要先安装nginx和unicorn

一 安装

安装nginx: sudo apt-get install nginx

安装unicorn: gem install unicorn

二 配置

1 在你项目的config文件夹下添加一个unicorn.rb文件,添加代码(样列:http://unicorn.bogomips.org/examples/unicorn.conf.rb)

我的如下:

 1 module Rails 2   class << self 3     def root 4       File.expand_path(__FILE__).split("/")[0..-3].join("/") 5     end 6   end 7 end 8  9 preload_app true10 working_directory Rails.root11 pid "#{Rails.root}/tmp/pids/unicorn.pid"12 stderr_path "#{Rails.root}/log/unicorn.log"13 stdout_path "#{Rails.root}/log/unicorn.log"14 15

16 worker_processes 2
17 timeout 3018 19 GC.respond_to?(:copy_on_write_friendly=) and 20   GC.copy_on_write_friendly = true21 22 before_fork do |server, worker|23   defined?(ActiveRecord::Base) and 24     ActiveRecord::Base.connection.disconnect!25 end26 27 after_fork do |server, worker|28   defined?(ActiveRecord::Base) and 29     ActiveRecord::Base.establish_connection30 end

2 配置nginx

sudo apt-get install nginx默认安装在/etc/nginx目前下

在/etc/nginx/conf.d目录下创建文件:project_name.conf 添加代码(样例: http://unicorn.bogomips.org/examples/nginx.conf )

我的如下:

 1 upstream project_name_backend { 2   server unix:/path_to_project/tmp/sockets/unicorn.project-name.sock fail_timeout=0; 3 } 4  5 server { 6   listen 80; 7   server_name localhost; 8   root /path_to_project/public; 9 10   location ^~ /assets/ {11     gzip_static on;12     expires max;13     add_header Cache-Control public;14   }15 16   try_files $uri/index.html $uri @unicorn;17   location @unicorn {18     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;19     proxy_set_header Host $http_host;20     proxy_redirect off;21     proxy_pass http://project_name_backend;22   }23 24   error_page 500 502 503 504 /500.html;25   client_max_body_size 4G;26   keepalive_timeout 10;27 }

注意:

1

listen "#{Rails.root}/tmp/sockets/unicorn.project-name.sock", :backlog => 64
upstream project_name_backend {    server unix:/path_to_project/tmp/sockets/unicorn.project-name.sock fail_timeout=0;  }

这两个的unicorn.project-name.sock的路径必须是一致的!!!

2

upstream project_name_backend 这里的project_name_backend 和 proxy_pass http://project_name_backend; 这里的project_name_backend是一致的!!!