Created
November 18, 2013 07:04
-
-
Save osulyanov/7523745 to your computer and use it in GitHub Desktop.
Nginx + Unicorn + Capistrano
http://habrahabr.ru/post/120368/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
load 'deploy' | |
# Uncomment if you are using Rails' asset pipeline | |
load 'deploy/assets' | |
load 'config/deploy' # remove this line to skip loading any of the default tasks |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rvm/capistrano' # Для работы rvm | |
require 'bundler/capistrano' # Для работы bundler. При изменении гемов bundler автоматически обновит все гемы на сервере, чтобы они в точности соответствовали гемам разработчика. | |
set :application, 'docs' | |
set :rails_env, 'production' | |
set :domain, '[email protected]' # Это необходимо для деплоя через ssh. Именно ради этого я настоятельно советовал сразу же залить на сервер свой ключ, чтобы не вводить паролей. | |
set :deploy_to, "/home/rails/apps/#{application}" | |
set :use_sudo, false | |
set :unicorn_conf, "#{deploy_to}/current/config/unicorn.rb" | |
set :unicorn_pid, "#{deploy_to}/shared/pids/unicorn.pid" | |
set :rvm_ruby_string, 'ruby-2.0.0-p247' # Это указание на то, какой Ruby интерпретатор мы будем использовать. | |
set :scm, :git # Используем git. | |
set :repository, '[email protected]:OSulyanov/docs.git' # Путь до вашего репозитария. | |
set :branch, 'master' # Ветка из которой будем тянуть код для деплоя. | |
set :deploy_via, :remote_cache # Указание на то, что стоит хранить кеш репозитария локально и с каждым деплоем лишь подтягивать произведенные изменения. | |
set :ssh_options, { :forward_agent => true } | |
role :web, domain | |
role :app, domain | |
role :db, domain, :primary => true | |
# интеграция rvm с capistrano настолько хороша, что при выполнении cap deploy:setup установит себя и указанный в rvm_ruby_string руби. | |
before 'deploy:setup', 'rvm:install_rvm', 'rvm:install_ruby' | |
after 'deploy:update_code', 'deploy:migrate' | |
after 'deploy:update_code', :roles => :app do | |
# Здесь для примера вставлен только один конфиг с приватными данными - database.yml. Обычно для таких вещей создают папку /srv/myapp/shared/config и кладут файлы туда. При каждом деплое создаются ссылки на них в нужные места приложения. | |
run "rm -f #{current_release}/config/database.yml" | |
run "ln -s #{deploy_to}/shared/config/database.yml #{current_release}/config/database.yml" | |
end | |
# Далее идут правила для перезапуска unicorn | |
namespace :deploy do | |
task :restart do | |
run "if [ -f #{unicorn_pid} ] && [ -e /proc/$(cat #{unicorn_pid}) ]; then kill -USR2 `cat #{unicorn_pid}`; else cd #{deploy_to}/current && bundle exec unicorn -c #{unicorn_conf} -E #{rails_env} -D; fi" | |
end | |
task :start do | |
run "bundle exec unicorn -c #{unicorn_conf} -E #{rails_env} -D" | |
end | |
task :stop do | |
run "if [ -f #{unicorn_pid} ] && [ -e /proc/$(cat #{unicorn_pid}) ]; then kill -QUIT `cat #{unicorn_pid}`; fi" | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
_ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
user rails; | |
worker_processes 4; | |
pid /var/run/nginx.pid; | |
events { | |
worker_connections 768; | |
# multi_accept on; | |
} | |
http { | |
## | |
# Basic Settings | |
## | |
sendfile on; | |
tcp_nopush on; | |
tcp_nodelay on; | |
keepalive_timeout 65; | |
types_hash_max_size 2048; | |
# server_tokens off; | |
# server_names_hash_bucket_size 64; | |
# server_name_in_redirect off; | |
include /etc/nginx/mime.types; | |
default_type application/octet-stream; | |
## | |
# Logging Settings | |
## | |
access_log /home/rails/log/nginx_access.log combined; | |
error_log /home/rails/log/nginx_error.log; | |
## | |
# Gzip Settings | |
## | |
gzip on; | |
gzip_disable "msie6"; | |
# gzip_vary on; | |
# gzip_proxied any; | |
# gzip_comp_level 6; | |
# gzip_buffers 16 8k; | |
# gzip_http_version 1.1; | |
# gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript; | |
## | |
# nginx-naxsi config | |
## | |
# Uncomment it if you installed nginx-naxsi | |
## | |
#include /etc/nginx/naxsi_core.rules; | |
## | |
# nginx-passenger config | |
## | |
# Uncomment it if you installed nginx-passenger | |
## | |
#passenger_root /usr; | |
#passenger_ruby /usr/bin/ruby; | |
## | |
# Virtual Host Configs | |
## | |
include /etc/nginx/conf.d/*.conf; | |
include /etc/nginx/sites-enabled/*; | |
} | |
#mail { | |
# # See sample authentication script at: | |
# # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript | |
# | |
# # auth_http localhost/auth.php; | |
# # pop3_capabilities "TOP" "USER"; | |
# # imap_capabilities "IMAP4rev1" "UIDPLUS"; | |
# | |
# server { | |
# listen localhost:110; | |
# protocol pop3; | |
# proxy on; | |
# } | |
# | |
# server { | |
# listen localhost:143; | |
# protocol imap; | |
# proxy on; | |
# } | |
#} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
upstream docsapp_server { | |
server unix:/home/rails/apps/docs/shared/unicorn.sock fail_timeout=0; | |
} | |
server { | |
listen 80 default deferred; # Опять же, если на одном и том же ip находится несколько серверов, то эта строка будет выглядеть как-то так myapp.mydomain.ru:80 | |
client_max_body_size 1G; | |
server_name test1.qlassic.ru; | |
keepalive_timeout 5; | |
root /home/rails/apps/docs/current/public; | |
try_files $uri/index.html $uri.html $uri @docsapp; | |
location @docsapp { | |
proxy_pass http://docsapp_server; | |
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; | |
proxy_set_header Host $http_host; | |
proxy_redirect off; | |
} | |
error_page 500 502 503 504 /500.html; | |
location = /500.html { | |
root /home/rails/apps/docs/current/public; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
deploy_to = "/home/rails/apps/docs" | |
rails_root = "#{deploy_to}/current" | |
pid_file = "#{deploy_to}/shared/pids/unicorn.pid" | |
socket_file= "#{deploy_to}/shared/unicorn.sock" | |
log_file = "#{rails_root}/log/unicorn.log" | |
err_log = "#{rails_root}/log/unicorn_error.log" | |
old_pid = pid_file + '.oldbin' | |
timeout 30 | |
worker_processes 4 # Здесь тоже в зависимости от нагрузки, погодных условий и текущей фазы луны | |
listen socket_file, :backlog => 1024 | |
pid pid_file | |
stderr_path err_log | |
stdout_path log_file | |
preload_app true # Мастер процесс загружает приложение, перед тем, как плодить рабочие процессы. | |
GC.copy_on_write_friendly = true if GC.respond_to?(:copy_on_write_friendly=) # Решительно не уверен, что значит эта строка, но я решил ее оставить. | |
before_exec do |server| | |
ENV["BUNDLE_GEMFILE"] = "#{rails_root}/Gemfile" | |
end | |
before_fork do |server, worker| | |
# Перед тем, как создать первый рабочий процесс, мастер отсоединяется от базы. | |
defined?(ActiveRecord::Base) and | |
ActiveRecord::Base.connection.disconnect! | |
# Ниже идет магия, связанная с 0 downtime deploy. | |
if File.exists?(old_pid) && server.pid != old_pid | |
begin | |
Process.kill("QUIT", File.read(old_pid).to_i) | |
rescue Errno::ENOENT, Errno::ESRCH | |
# someone else did our job for us | |
end | |
end | |
end | |
after_fork do |server, worker| | |
# После того как рабочий процесс создан, он устанавливает соединение с базой. | |
defined?(ActiveRecord::Base) and | |
ActiveRecord::Base.establish_connection | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment