Load balancing with Nginx And Unicorn

Nginx is a pretty awesome lightweight Web Server for Linux. You can use it to deliver static web content. But you can use at as a load balancer, too. If you have a Ruby on Rails Application running on multiple unicorn servers, than Nginx can do the load balancing for the unicorn servers.

Just add the following lines to your “/etc/nginx/conf.d/default.conf”:

upstream unicorns { 
  ip_hash; 
  server XXX.XXX.XXX.XXX:8080; 
  server <IP_ADDRESS>:<PORT>; 
}

XXX stands for an IP Address. You can add as many server lines as you want. The “ip_hash” is not mandatory. This just if you want to force nginx to send the requests from a particular user every time to the same app server. If your Web Application is REST ful and Stateless you don’t need it. Otherwise you should add the line.

Now you just have to add one block for your domain:

server {
  listen 80;
  server_name my-awesome-domain.com;
  location / { 
    proxy_pass http://unicorns; 
  } 
}

And that’s it.

One more thing. If you want limit the file upload size or you have problems with big HTML5 AJAX requests, you should add a little bit more. Here is a more complete example:

server {
  listen 80;
  server_name my-awesome-domain.com;
  client_max_body_size 1M; 
  proxy_buffer_size 128k; 
  proxy_buffers 4 256k; 
  proxy_busy_buffers_size 256k; 
  location / { 
    proxy_pass http://unicorns; 
  } 
}

Unicorn Starting Problems

After I installed fresh unicorn I got this error message by starting “unicorn_rails”

Could not find activesupport-3.1.0 in any of the sources

I still don’t know what was exactly the problem. But after I closed the terminal and opened a new one, everything worked fine.

Unicorn

Unicorn is a pretty cool and super fast HTTP Server for Rack applications. You can install it with this command:

gem install unicorn

and you can run you Ruby on Rails app on it with this command:

<RAILS_ROOT>: unicorn_rails

Just navigate into your root app directory and type in “unicorn_rails”. By default it will run the server on Port 8080 and you app is available on:

http://localhost:8080

Unicorn is optimized for Linux/Unix machines! You can not run your JRuby app on it, because some native extensions are not yet implemented for JRuby.