Nginx + unicorn 运行多个Rails应用程序

时间:2022-06-15 16:09:06

PS:第一次写的很详细,可惜发布失败,然后全没了,这是第二次,表示只贴代码,剩下的自己领悟好了,这就是所谓的一鼓作气再而衰吧,希望没有第三次。

版本:

  ruby 2.1.0

  rails 4.0.2

  nginx 1.5.8 mainline version

  unicorn 4.7.0

/usr/local/nginx/conf/nginx.conf

 user NginxUser NginxGroup;
worker_processes ; events {
worker_connections ;
} http {
include mime.types;
include /usr/local/nginx/conf/conf.d/*.conf;
default_type application/octet-stream; sendfile on;
#tcp_nopush on; keepalive_timeout 65; gzip on;
}

/usr/local/nginx/conf/conf.d/guorj.conf

 upstream guorj_rails_unicorn_server {
server unix:/tmp/guorj_unicorn.sock fail_timeout=;
#server 127.0.0.1: fail_timeout=;
}
server {
listen ;
client_max_body_size 4G;
server_name guorj.com;
keepalive_timeout ;
root /home/NginxUser/www/guorj/public;
access_log /home/NginxUser/www/guorj/log/nginx_access.log;
error_log /home/NginxUser/www/guorj/log/nginx_error.log;
rewrite_log on;
index index.html; location / {
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_buffering on;
proxy_redirect off;
proxy_pass http://guorj_rails_unicorn_server;
}
#Rails error pages
location =/.html {
root /home/NginxUser/www/guorj/public;
}
}

/home/NginxUser/www/guorj/config/unicorn.rb

 # Sample verbose configuration file for Unicorn (not Rack)
#
# This configuration file documents many features of Unicorn
# that may not be needed for some applications. See
# http://unicorn.bogomips.org/examples/unicorn.conf.minimal.rb
# for a much simpler configuration file.
#
# See http://unicorn.bogomips.org/Unicorn/Configurator.html for complete
# documentation.
# can't specify rails env
rails_env = ENV["RAILS_ENV"] || "production" # Use at least one worker per core if you're on a dedicated server,
# more will usually help for _short_ waits on databases/caches.
worker_processes 4 # Since Unicorn is never exposed to outside clients, it does not need to
# run on the standard HTTP port (80), there is no reason to start Unicorn
# as root unless it's from system init scripts.
# If running the master process as root and the workers as an unprivileged
# user, do this to switch euid/egid in the workers (also chowns logs):
# user "unprivileged_user", "unprivileged_group" # Help ensure your application will always spawn in the symlinked
# "current" directory that Capistrano sets up. app_root = File.expand_path('.') working_directory app_root #"/path/to/app/current" # available in 0.94.0+ # listen on both a Unix domain socket and a TCP port,
# we use a shorter backlog for quicker failover when busy
#listen "/path/to/.unicorn.sock", :backlog => 64
#listen "#{app_root}/tmp/sockets/unicorn.sock", :backlog => 64
listen "/tmp/guorj_unicorn.sock", :backlog => 64
listen 8081, :tcp_nopush => false # true # nuke workers after 30 seconds instead of 60 seconds (the default)
timeout 120 # # feel free to point this anywhere accessible on the filesystem
#pid "/path/to/app/shared/pids/unicorn.pid"
#pid "#{app_root}/tmp/pids/unicorn.pid"
pid "/tmp/guorj_unicorn.pid" # By default, the Unicorn logger will write to stderr.
# Additionally, ome applications/frameworks log to stderr or stdout,
# so prevent them from going to /dev/null when daemonized here:
#stderr_path "/path/to/app/shared/log/unicorn.stderr.log"
#stdout_path "/path/to/app/shared/log/unicorn.stdout.log"
stderr_path "#{app_root}/log/unicorn.stderr.log"
stdout_path "#{app_root}/log/unicorn.stdout.log" # combine Ruby 2.0.0dev or REE with "preload_app true" for memory savings
# http://rubyenterpriseedition.com/faq.html#adapt_apps_for_cow
preload_app true
GC.respond_to?(:copy_on_write_friendly=) and
GC.copy_on_write_friendly = true # Enable this flag to have unicorn test client connections by writing the
# beginning of the HTTP headers before calling the application. This
# prevents calling the application for connections that have disconnected
# while queued. This is only guaranteed to detect clients on the same
# host unicorn runs on, and unlikely to detect disconnects even on a
# fast LAN.
# check_client_connection false before_fork do |server, worker|
# the following is highly recomended for Rails + "preload_app true"
# as there's no need for the master process to hold a connection
defined?(ActiveRecord::Base) and
ActiveRecord::Base.connection.disconnect! # The following is only recommended for memory/DB-constrained
# installations. It is not needed if your system can house
# twice as many worker_processes as you have configured.
#
# # This allows a new master process to incrementally
# # phase out the old master process with SIGTTOU to avoid a
# # thundering herd (especially in the "preload_app false" case)
# # when doing a transparent upgrade. The last worker spawned
# # will then kill off the old master process with a SIGQUIT.
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
#
# Throttle the master from forking too quickly by sleeping. Due
# to the implementation of standard Unix signal handlers, this
# helps (but does not completely) prevent identical, repeated signals
# from being lost when the receiving process is busy.
sleep 1
end after_fork do |server, worker|
# per-process listener ports for debugging/admin/migrations
# addr = "127.0.0.1:#{9293 + worker.nr}"
# server.listen(addr, :tries => -1, :delay => 5, :tcp_nopush => true) # the following is *required* for Rails + "preload_app true",
defined?(ActiveRecord::Base) and
ActiveRecord::Base.establish_connection # if preload_app is true, then you may also want to check and
# restart any other shared sockets/descriptors such as Memcached,
# and Redis. TokyoCabinet file handles are safe to reuse
# between any number of forked children (assuming your kernel
# correctly implements pread()/pwrite() system calls)
end

然后运行unicorn

unicorn_rails -c /home/NginxUser/www/guorj/config/unicorn.rb -E production -D 

添加第二个rails项目(请自行和第一个项目的配置对比不同,被网速把激情磨灭了)

/usr/local/nginx/conf/conf.d/wguorj.conf

 upstream wguorj_rails_unicorn_server {
server unix:/tmp/wguorj_unicorn.sock fail_timeout=;
#server 127.0.0.1: fail_timeout=;
}
server {
listen ;
client_max_body_size 4G;
server_name www.guorj.com;
keepalive_timeout ;
root /home/NginxUser/www/wguorj/public;
access_log /home/NginxUser/www/wguorj/log/nginx_access.log;
error_log /home/NginxUser/www/wguorj/log/nginx_error.log;
rewrite_log on;
index index.html; location / {
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_buffering on;
proxy_redirect off;
proxy_pass http://wguorj_rails_unicorn_server;
}
#Rails error pages
location =/.html {
root /home/NginxUser/www/wguorj/public;
}
}

/home/NginxUser/www/wguorj/config/unicorn.rb

 # Sample verbose configuration file for Unicorn (not Rack)
#
# This configuration file documents many features of Unicorn
# that may not be needed for some applications. See
# http://unicorn.bogomips.org/examples/unicorn.conf.minimal.rb
# for a much simpler configuration file.
#
# See http://unicorn.bogomips.org/Unicorn/Configurator.html for complete
# documentation.
# can't specify rails env
rails_env = ENV["RAILS_ENV"] || "production" # Use at least one worker per core if you're on a dedicated server,
# more will usually help for _short_ waits on databases/caches.
worker_processes 4 # Since Unicorn is never exposed to outside clients, it does not need to
# run on the standard HTTP port (80), there is no reason to start Unicorn
# as root unless it's from system init scripts.
# If running the master process as root and the workers as an unprivileged
# user, do this to switch euid/egid in the workers (also chowns logs):
# user "unprivileged_user", "unprivileged_group" # Help ensure your application will always spawn in the symlinked
# "current" directory that Capistrano sets up. app_root = File.expand_path('.') working_directory app_root #"/path/to/app/current" # available in 0.94.0+ # listen on both a Unix domain socket and a TCP port,
# we use a shorter backlog for quicker failover when busy
#listen "/path/to/.unicorn.sock", :backlog => 64
#listen "#{app_root}/tmp/sockets/unicorn.sock", :backlog => 64
listen "/tmp/wguorj_unicorn.sock", :backlog => 64
listen 8082, :tcp_nopush => false # true # nuke workers after 30 seconds instead of 60 seconds (the default)
timeout 120 # # feel free to point this anywhere accessible on the filesystem
#pid "/path/to/app/shared/pids/unicorn.pid"
#pid "#{app_root}/tmp/pids/unicorn.pid"
pid "/tmp/wguorj_unicorn.pid" # By default, the Unicorn logger will write to stderr.
# Additionally, ome applications/frameworks log to stderr or stdout,
# so prevent them from going to /dev/null when daemonized here:
#stderr_path "/path/to/app/shared/log/unicorn.stderr.log"
#stdout_path "/path/to/app/shared/log/unicorn.stdout.log"
stderr_path "#{app_root}/log/unicorn.stderr.log"
stdout_path "#{app_root}/log/unicorn.stdout.log" # combine Ruby 2.0.0dev or REE with "preload_app true" for memory savings
# http://rubyenterpriseedition.com/faq.html#adapt_apps_for_cow
preload_app true
GC.respond_to?(:copy_on_write_friendly=) and
GC.copy_on_write_friendly = true # Enable this flag to have unicorn test client connections by writing the
# beginning of the HTTP headers before calling the application. This
# prevents calling the application for connections that have disconnected
# while queued. This is only guaranteed to detect clients on the same
# host unicorn runs on, and unlikely to detect disconnects even on a
# fast LAN.
# check_client_connection false before_fork do |server, worker|
# the following is highly recomended for Rails + "preload_app true"
# as there's no need for the master process to hold a connection
defined?(ActiveRecord::Base) and
ActiveRecord::Base.connection.disconnect! # The following is only recommended for memory/DB-constrained
# installations. It is not needed if your system can house
# twice as many worker_processes as you have configured.
#
# # This allows a new master process to incrementally
# # phase out the old master process with SIGTTOU to avoid a
# # thundering herd (especially in the "preload_app false" case)
# # when doing a transparent upgrade. The last worker spawned
# # will then kill off the old master process with a SIGQUIT.
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
#
# Throttle the master from forking too quickly by sleeping. Due
# to the implementation of standard Unix signal handlers, this
# helps (but does not completely) prevent identical, repeated signals
# from being lost when the receiving process is busy.
sleep 1
end after_fork do |server, worker|
# per-process listener ports for debugging/admin/migrations
# addr = "127.0.0.1:#{9293 + worker.nr}"
# server.listen(addr, :tries => -1, :delay => 5, :tcp_nopush => true) # the following is *required* for Rails + "preload_app true",
defined?(ActiveRecord::Base) and
ActiveRecord::Base.establish_connection # if preload_app is true, then you may also want to check and
# restart any other shared sockets/descriptors such as Memcached,
# and Redis. TokyoCabinet file handles are safe to reuse
# between any number of forked children (assuming your kernel
# correctly implements pread()/pwrite() system calls)
end

运行第二个rails程序 记得重启nginx

unicorn_rails -c /home/NginxUser/www/wguorj/config/unicorn.rb -E production -D

相关参考资料

求 Nginx + Unicorn 部署 Rails 完整配置 http://ruby-china.org/topics/471

https://github.com/huacnlee/ruby-china/blob/master/config/unicorn.rb

https://raw.github.com/defunkt/unicorn/master/examples/unicorn.conf.rb

unicorn官网:http://unicorn.bogomips.org/

http://ruby-china.org/topics/10895

Nginx+Unicorn+rails多项目 http://chinacheng.iteye.com/blog/757638

Ruby-China.org 选择用 Thin 还是 Unicorn? http://ruby-china.org/topics/35

使用Unicorn替代Mongrel作为Ruby on Rails的服务器 http://www.cslog.cn/Content/unicorn-for-ruby-on-rails/

貌似要先启动nginx 然后再启动所有的unicorn 否则会有问题 不知道是不是真的 再继续观察

touch /tmp/restart.txt 重启当前的Rails项目 http://ruby-china.org/topics/1374

touch tmp/restart.txt
其实也能实现优雅的重启 Unicorn 进程。http://ruby-china.org/topics/35#reply32

注运行两个rails项目的进程

[root@GrjServer guorj]# ps aux | grep nginx
root 0.0 0.2 ? Ss : : nginx: master process /usr/local/nginx/sbin/nginx
0.0 0.3 ? S : : nginx: worker process
root 0.0 0.1 pts/ S+ : : grep nginx
[root@GrjServer guorj]# ps aux | grep unicorn
root 0.0 12.5 ? Sl : : unicorn_rails master -c /home/NginxUser/www/guorj/config/unicorn.rb -E production -D
root 0.0 12.3 ? Sl : : unicorn_rails worker[] -c /home/NginxUser/www/guorj/config/unicorn.rb -E production -D
root 0.0 12.3 ? Sl : : unicorn_rails worker[] -c /home/NginxUser/www/guorj/config/unicorn.rb -E production -D
root 0.0 12.3 ? Sl : : unicorn_rails worker[] -c /home/NginxUser/www/guorj/config/unicorn.rb -E production -D
root 0.0 12.3 ? Sl : : unicorn_rails worker[] -c /home/NginxUser/www/guorj/config/unicorn.rb -E production -D
root 1.2 12.5 ? Sl : : unicorn_rails master -c /home/NginxUser/www/wguorj/config/unicorn.rb -E production -D
root 0.0 12.3 ? Sl : : unicorn_rails worker[] -c /home/NginxUser/www/wguorj/config/unicorn.rb -E production -D
root 0.0 12.3 ? Sl : : unicorn_rails worker[] -c /home/NginxUser/www/wguorj/config/unicorn.rb -E production -D
root 0.0 12.3 ? Sl : : unicorn_rails worker[] -c /home/NginxUser/www/wguorj/config/unicorn.rb -E production -D
root 0.0 12.3 ? Sl : : unicorn_rails worker[] -c /home/NginxUser/www/wguorj/config/unicorn.rb -E production -D
root 0.0 0.1 pts/ S+ : : grep unicorn
[root@GrjServer guorj]#