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; 
  } 
}

One thought on “Load balancing with Nginx And Unicorn

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s