Tuesday, December 10, 2013

Setting up Unicorn + Ngnix in Ubuntu for Ruby on Rails

To get you started, Let’s install Nginx first by using apt-get package manager.
$ sudo apt-get install nginx
Sometime you get ERROR because your machine packages are not upto date. Run apt-get update to downloads the package lists from the repositories and “updates” them to get information on the newest versions of packages and their dependencies. It will do this for all repositories and PPAs.
$ sudo apt-get update
Once your nignx will install, you command window will prompt:
Setting up nginx-full (1.2.1-2.2ubuntu0.1) ...
Setting up nginx (1.2.1-2.2ubuntu0.1) ...
Processing triggers for libc-bin ...
ldconfig deferred processing now taking place
Processing triggers for sgml-base ...
Updating the super catalog...

At this point switch to /etc/nginx/ and /etc/nginx/sites-available configuration directory and have a look to nginx.conf and default respective configuration file. It’s self explanatory under commented in-lines. If still you need more details. I will recommend you to check wiki.nginx for more info.
While the server configuration it’s always better to create separate user(which we have more control over than nobody) for security reasons and increased control by using below command:
$ sudo useradd -s /sbin/nologin -r nginx
$ sudo usermod -a -G web nginx
Starting/stopping/restarting Nginx is pretty straight forward.
$ sudo service nginx start/restart/stop
Now let’s install Unicorn, Unicorn is distributed as ruby gem So you can install vi ruby gem.
$ gem install unicorn
Once Unicorn installed successfully. We need to create two configuration file.
1.Replace /etc/nginx/sites-available/ default file with below code:
upstream shop {
server unix:/tmp/unicorn.shop.sock fail_timeout=0;
}

server {
listen 80;# default deferred;
server_name localhost;
root /var/www/shop/public;
try_files $uri/index.html $uri @shop;
location @shop {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://shop;
}
error_page 500 502 503 504 /500.html;
client_max_body_size 4G;
keepalive_timeout 10;
}

2. Create a unicorn.config file in your Rails application configuration file with below code:
working_directory "/var/www/shop"
pid "/var/www/shop/tmp/pids/unicorn.pid"
stderr_path "/var/www/shop/log/unicorn.log"
stdout_path "/var/www/shop/log/unicorn.log"

listen "/tmp/unicorn.shop.sock"
worker_processes 2
timeout 30

You have to tweak a few things to set the right paths in above configuration. Change “/var/www/shop” with your rails application directory.
In my case my Rails application is in /var/www/ with shop name.
Before start your rails application, make sure to include unicorn gem in your Gemfile and run bundle to install all dependencies.

No comments: