customize Nginx global directives with Capistrano

If you’re using Capistrano to maintain an Nginx-based deployment, you’ve probably searched around for a helpful gem or two.  Personally, I like this gem so far:

It offers the easiest configuration if you’re used to rvm as your Ruby package manager.  I think it handles rbenv well judging by some comments, not so sure about chruby.

Anyway, there are several gems out there for this but they all seem to only offer configuration for a virtual server that is added to the /etc/nginx/sites-available (and then symlinked from /etc/nginx/sites-enabled).

What if you would like to customize Nginx global directives that exist outside of a http or server block and therefore not inherited by your custom server directives?

Two such useful directives for tuning the performance of Nginx are `worker_processes` and `worker_connections`.

Here’s an example task to add to your config/deploy.rb file that you can customize as you need.  In my case, my Ubuntu server installed a default /etc/nginx/nginx.conf file that had set `worker_processes` to 4 (too high as only one core) and `worker_connections` to 768 (too low for the box).

namespace :myapp do
  desc "Install Nginx"
  task :install_nginx do
    on roles(:web, :app), in: :sequence, wait: 10 do
      execute "sudo apt-get install nginx-full -y"

  desc "Tune Nginx config"
  task :tweak_nginx_config do
    on roles(:web, :app), in: :sequence, wait: 10 do
      execute "sudo perl -i -pe's|worker_processes 4|worker_processes 1|' /etc/nginx/nginx.conf"
      execute "sudo perl -i -pe's|worker_connections 768|worker_connections 1024|' /etc/nginx/nginx.conf"

before 'deploy', 'gonebusy:install_nginx'
before 'deploy', 'gonebusy:tweak_nginx_config'

And there you have it!  Now onto tweaking our server config via the above gems useful variables…

Leave a Reply

Your email address will not be published. Required fields are marked *