Tuesday, 27 May 2014

Configuration Unicorn over nginx

Nginx Using Rails
Nginx is an open source reverse proxy server for HTTP, HTTPS, SMTP, POP3, and IMAP protocols, as well as a load balancer, HTTP cache, and a web server.

How it works
Nginx works on event driven architecture. it means that notifications or signals are used to mark the initiation or completion of a process. Thus, the resources can be used by other process until a process initiation event is triggered and resource can be allocated and released dynamically. This leads to the optimized use of memory and CPU. Nginx doesn’t create a new process for a new request.
Nginx has one master process and several worker processes. The main purpose of the master process is to read and evaluate configuration, and maintain worker processes. Worker processes do actual processing of requests. nginx has focused on high performance, high concurrency and low memory usage.

Write the following code on your local machine config/unicorn.rb
listen ""
worker_processes 4
preload_app true
user 'vagrant'
root = "/home/vagrant/app/sample_app/current"
working_directory root
pid "#{root}/tmp/pids/"
stderr_path "#{root}/log/unicorn.log"
stdout_path "#{root}/log/unicorn.log"

# listen "/tmp/unicorn.sample_app.sock"
timeout 30
user: set user name of the server.
working_directory: path to the application.
listen: Url which will communicate with nginx.

Nginx Configuration:
On server machine, open `vi /etc/nginx/nginx.conf` and paste the below code.
worker_processes 1;
user vagrant;
pid /tmp/;
error_log /home/vagrant/app/sample_app/shared/log/nginx.error.log;

events {
  worker_connections 1024; # increase if you have lots of clients
  accept_mutex off; # "on" if nginx worker_processes > 1

http {
  include mime.types;
  default_type application/octet-stream;
  access_log  /home/vagrant/app/sample_app/shared/log/nginx.access.log combined;
  sendfile on;
  tcp_nopush on; # off may be better for *some* Comet/long-poll stuff
  tcp_nodelay off; # on may be better for some Comet/long-poll stuff

  upstream app_server {

  server {
    client_max_body_size 4G;
    server_name localhost;
    keepalive_timeout 600s;
    root /home/vagrant/app/sample_app/current;
    try_files $uri/index.html $uri.html $uri @app;

    location @app {
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_redirect off;
      proxy_pass http://app_server;

    # Rails error pages
    error_page 500 502 503 504 /500.html;
    location = /500.html {
      root /home/vagrant/app/sample_app/current;
   `upstream` should have the IP or path that is given in unicorn `listen`.