nginx + mongrel installation and configuration for RoR app.

I’m going to compile in nginx server from the source. I’m assuming that you’ve packages like ruby, Rails etc. pre-installed on your system/server.

I’ve compiled in nginx from the source, so you’ll need a gcc complier.

Download the source.
wget http://sysoev.ru/nginx/nginx-0.5.35.tar.gz

Untar it
tar zxvf nginx-0.5.35.tar.gz

Run.

cd nginx-0.5.35
./configure --prefix=/usr/local/nginx
make
make install

If everything does fine, nginx will get installed /usr/local/nginx

Here is a sample nginx configuration file. Just copy it as nginx.conf(/usr/local/nginx/conf/nginx.conf) and modify it accordingly four your application setup.

user  www www;
worker_processes  3;

error_log  /var/log/nginx/error.log;

pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /usr/local/nginx/conf/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] $status '
                      '"$request" $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    tcp_nopush     on;
    tcp_nodelay    on;

        gzip  on;
    upstream mongrel {
     server 127.0.0.1:4000;
     server 127.0.0.1:4001;
    }

        #Rails App here
            server {
        listen       80;
        root /var/www/railsapp/public;
        index index.html index.htm;
        server_name yourdomain.com www.yourdomain.com;
        client_max_body_size 50M;

        access_log  /var/log/nginx/localhost.access.log;

        location / {
         proxy_set_header X-Real-IP $remote_addr;
         proxy_set_header X-Forwarded_for $proxy_add_x_forwarded_for;
         proxy_set_header Host $http_host;
         proxy_redirect false;
         proxy_max_temp_file_size 0;

         if (-f $request_filename) {
            break;
          }
         if (-f $request_filename/index.html) {
            rewrite (.*) $1/index.html break;
         }
         if (-f $request_filename.html) {
            rewrite (.*) $1.html break;
         }
         if (!-f $request_filename) {
            proxy_pass http://mongrel;
            break;
         }

        }
        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /500.html;
        location = /500.html {
            root  /var/www/railsapp/public;
        }
    }

}

You may start the nginx server using the command

/usr/local/nginx/bin/nginx -c /usr/local/nginx/conf/nginx.conf

Now you may want an init startup script to start|stop|restart the server. Just copy the below script as /etc/init.d/nginx and set it executable(chmod 755 /etc/init.d/nginx)

#!/bin/sh

# Description: Startup script for nginx webserver on Debian. Place in /etc/init.d and
# run 'sudo update-rc.d nginx defaults', or use the appropriate command on your
# distro.
#
# Author:       Ryan Norbauer
# Modified:     Geoffrey Grosenbach http://topfunky.com

set -e

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DESC="nginx daemon"
NAME=nginx
DAEMON=/usr/local/nginx/sbin/$NAME
CONFIGFILE=/usr/local/nginx/conf/nginx.conf
PIDFILE=/var/run/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME

# Gracefully exit if the package has been removed.
test -x $DAEMON || exit 0

d_start() {
  $DAEMON -c $CONFIGFILE || echo -n " already running"
}

d_stop() {
  kill -QUIT `cat $PIDFILE` || echo -n " not running"
}

d_reload() {
  kill -HUP `cat $PIDFILE` || echo -n " can't reload"
}

case "$1" in
  start)
        echo -n "Starting $DESC: $NAME"
        d_start
        echo "."
        ;;
  stop)
        echo -n "Stopping $DESC: $NAME"
        d_stop
        echo "."
        ;;
  reload)
        echo -n "Reloading $DESC configuration..."
        d_reload
        echo "reloaded."
  ;;
  restart)
        echo -n "Restarting $DESC: $NAME"
        d_stop
        # One second might not be time enough for a daemon to stop,
        # if this happens, d_start will fail (and dpkg will break if
        # the package is being upgraded). Change the timeout if needed
        # be, or change d_stop to have start-stop-daemon use --retry.
        # Notice that using --retry slows down the shutdown process somewhat.
        sleep 1
        d_start
        echo "."
        ;;
  *)
          echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
          exit 3
        ;;
esac

exit 0

Also don’t forget to add the user www using “useradd -s /sbin/nologin www” if the user doesn’t exists.

Now time to setup mongrel for your app. Install the mongrel gem, if it’s not installed already.

gem install mongrel

Then configure the mongrel cluster for your app and start the mongrel server.

cd /var/www/railsapp (your application directory)

mongrel_rails cluster::configure -e production -p 4000 -N 2

mongrel_rails cluster::start

You can of course use the mongrel_rails cluster::start|stop|restart commands to manage your mongrel instance.

Hope that this tutorial is useful…

Monitoring nginx Server Statistics With rrdtool

This script is very easy to install and configure. You can use following steps to get pretty stats graph for your nginx-powered server:

  • Modify your nginx config file and add following location to it:
http {

server {
listen SOME.IP.ADD.RESS;

location /nginx_status {
stub_status on;
access_log   off;
allow SOME.IP.ADD.RESS;
deny all;
}

}

}
 * Test your config file with following command:
 # /your/installation/sbin/nginx -t
2006/04/29 04:24:36 [info] 31676#0: the configuration file /opt/nginx/conf/nginx.conf syntax is ok
2006/04/29 04:24:36 [info] 31676#0: the configuration file /opt/nginx/conf/nginx.conf was tested successfully
#
If you will get error about stub_status directive, check your nginx – it should be configured with —-with-http_stub_status_module option.

  • If your configuration is OK, you can restart nginx and test it:
  •  # GET http://your-domain.com/nginx_status
    Active connections: 1492
    server accepts handled requests
    2124355 2124355 8278635
    Reading: 6 Writing: 405 Waiting: 1081
     Download  perl script: rrd_nginx.pl and make it executable with
    # chmod +x rrd_nginx.pl
     Change settings in rrd_nginx.pl to let script know where it will save rrd-base and images:
     #!/usr/bin/perl
    use RRDs;
    use LWP::UserAgent;

    # define location of rrdtool databases
    my $rrd = ‘/opt/rrd’;
    # define location of images
    my $img = ‘/opt/rrd/html’;
    # define your nginx stats URL
    my $URL = http://your-domain.com/nginx_status”;

     Last step is to insert following string to /etc/crontab file and to restart cron daemon:
    * *     * * *   root    /some/path/rrd_nginx.pl  When all preparations will be finished, you get  images in your $img directory: ---------------------  Quoted from blog.kovyrin.net

    Nginx HTTP(S) Reverse Proxy/Web Server

    This post with list of typical nginx configurations and example configuration snippets for these configurations.

    All sample configuration files are tested on up to date version of nginx, which has been compiled and installed with following commands:

    # ./configure –prefix=/usr/local/nginx –with-http_ssl_module
    # make
    # make install

    Using nginx as web server with PHP support

    If you need to use nginx with PHP, you can setup PHP as FastCGI and let nginx to forward all PHP queries to some FastCGI port (tcp/socket). To use this configuration you need to start PHP as FastCGI using some third party software like spawn-fcgi from lighttpd

    To enable PHP support, you need to add special location section to your config file:

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    location ~ \.php$ {
    fastcgi_pass   127.0.0.1:12345;
    fastcgi_index  index.php;

    fastcgi_param  SCRIPT_FILENAME  /usr/local/nginx/html$fastcgi_script_name;
    fastcgi_param  QUERY_STRING     $query_string;
    fastcgi_param  REQUEST_METHOD   $request_method;
    fastcgi_param  CONTENT_TYPE     $content_type;
    fastcgi_param  CONTENT_LENGTH   $content_length;
    }

    ——————-
    Using nginx as web server with SSI support

    Server-Side Includes (aka SSI) is another interesting feature of nginx. As for now, following ssi instructions are supported: config, echo, if, include, set.

    SSI support can be anabled by single line configuration command in your config file:

    location / {
    ssi  on;

    }
    Using nginx as https-enabled web server

    You need https-access to your Nginx-powered site? No problems! Nginx supports https and can be used to implement secured web-server with SSLv2, SSLv3 or TLSv1.

    To enable https-support you should have certificate and key files. How to obtain them, you can read in SSL FAQ. When you will obtain them, you can enable ssl-module:

    server {
    listen               443;
    ssl                  on;
    ssl_certificate      /usr/local/nginx/conf/cert.pem;
    ssl_certificate_key  /usr/local/nginx/conf/cert.key;
    keepalive_timeout    70;

    }
    Using nginx as reverse-proxy server before some another web-server

    If you have some large web-site and you have noticed, that your Apache can not handle more load, you can put nginx before your primary web-server to use it as light reverse-proxy and as web-server to handle requests to static files.

    Thanks to nginx flexibility, you can pass any types of requests to backend server by using location sections (all files, only dynamic content requests or some specific locations in your web-server tree):

    location / {
    proxy_pass        http://localhost:8000/;
    proxy_set_header  X-Real-IP  $remote_addr;
    }
    Using nginx for virtual hosting platforms

    One of the interesting use cases for Nginx is virtual hosting platform because it meets all requirements for good hosting server: it is efficient, it supports all popular virtual hosting methods and it has very good internal structure, so it can be easily extended in for any specific areas.

    As for now, it is being used by many hosting companies as reverse proxy and I am using it on my free hosting service with millions unique visitors per day.

    If you vant to try virtual hosting feature, you can create additional server sections in your config file (first section will be default):

    http {
    server {
    listen  192.168.10.1;
    listen  192.168.10.1:8000;

    server_name   one.example.com  http://www.one.example.com;

    }

    server {
    listen  192.168.10.1;
    listen  192.168.10.2:8000;
    listen  9000;

    server_name   two.example.com  http://www.two.example.com
    three.example.com  http://www.three.example.com;

    }

    server {
    listen  9000;

    server_name   four.example.com  http://www.four.example.com;

    }
    }

     Quoted from
    This post with list of typical nginx configurations and example configuration snippets for these configurations.

    All sample configuration files are tested on up to date version of nginx, which has been compiled and installed with following commands:

    # ./configure –prefix=/usr/local/nginx –with-http_ssl_module
    # make
    # make install

    Using nginx as web server with PHP support

    If you need to use nginx with PHP, you can setup PHP as FastCGI and let nginx to forward all PHP queries to some FastCGI port (tcp/socket). To use this configuration you need to start PHP as FastCGI using some third party software like spawn-fcgi from lighttpd

    To enable PHP support, you need to add special location section to your config file:

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    location ~ \.php$ {
    fastcgi_pass   127.0.0.1:12345;
    fastcgi_index  index.php;

    fastcgi_param  SCRIPT_FILENAME  /usr/local/nginx/html$fastcgi_script_name;
    fastcgi_param  QUERY_STRING     $query_string;
    fastcgi_param  REQUEST_METHOD   $request_method;
    fastcgi_param  CONTENT_TYPE     $content_type;
    fastcgi_param  CONTENT_LENGTH   $content_length;
    }

    ——————-
    Using nginx as web server with SSI support

    Server-Side Includes (aka SSI) is another interesting feature of nginx. As for now, following ssi instructions are supported: config, echo, if, include, set.

    SSI support can be anabled by single line configuration command in your config file:

    location / {
    ssi  on;

    }
    Using nginx as https-enabled web server

    You need https-access to your Nginx-powered site? No problems! Nginx supports https and can be used to implement secured web-server with SSLv2, SSLv3 or TLSv1.

    To enable https-support you should have certificate and key files. How to obtain them, you can read in SSL FAQ. When you will obtain them, you can enable ssl-module:

    server {
    listen               443;
    ssl                  on;
    ssl_certificate      /usr/local/nginx/conf/cert.pem;
    ssl_certificate_key  /usr/local/nginx/conf/cert.key;
    keepalive_timeout    70;

    }
    Using nginx as reverse-proxy server before some another web-server

    If you have some large web-site and you have noticed, that your Apache can not handle more load, you can put nginx before your primary web-server to use it as light reverse-proxy and as web-server to handle requests to static files.

    Thanks to nginx flexibility, you can pass any types of requests to backend server by using location sections (all files, only dynamic content requests or some specific locations in your web-server tree):

    location / {
    proxy_pass        http://localhost:8000/;
    proxy_set_header  X-Real-IP  $remote_addr;
    }
    Using nginx for virtual hosting platforms

    One of the interesting use cases for Nginx is virtual hosting platform because it meets all requirements for good hosting server: it is efficient, it supports all popular virtual hosting methods and it has very good internal structure, so it can be easily extended in for any specific areas.

    As for now, it is being used by many hosting companies as reverse proxy and I am using it on my free hosting service with millions unique visitors per day.

    If you vant to try virtual hosting feature, you can create additional server sections in your config file (first section will be default):

    http {
    server {
    listen  192.168.10.1;
    listen  192.168.10.1:8000;

    server_name   one.example.com  http://www.one.example.com;

    }

    server {
    listen  192.168.10.1;
    listen  192.168.10.2:8000;
    listen  9000;

    server_name   two.example.com  http://www.two.example.com
    three.example.com  http://www.three.example.com;

    }

    server {
    listen  9000;

    server_name   four.example.com  http://www.four.example.com;

    }

    )
     Quoted from blog.kovyrin.net

    HOWTO: Install WordPress on Nginx

    Apache is a very well-establish web server that can handle just about any situation. Unfortunately, that flexibility comes at the cost of size and relatively high demands on server resources. Nginx (“engine x”) is a lightweight web server/reverse proxy that is very efficient and perfect for hosting WordPress. Read on to see how that can be done…

    Step One: FastCGI

    First off, Nginx does not provide FastCGI for you (FastCGI is what your web server uses to interact with WordPress’s PHP code), so you’ve got to have a way to spawn your own FastCGI processes. My preferred method is to use the spawn-fcgi program provided by the web server lighttpd. You can use PHP’s built-in FastCGI manager php-cgi to do the same thing, but it’s not as straight-forward. Plus, if you learn how to use spawn-fcgi, you can easily adapt it for use with other web applications requiring FastCGI.

    Install spawn-fcgi

    To download and install spawn-fcgi, run the following commands. Don’t worry, all of the building happens in your current directory…nothing else will be installed on your machine.

    $ wget http://www.lighttpd.net/download/lighttpd-1.4.18.tar.bz2
    $ tar -xvjf lighttpd-1.4.18.tar.bz2
    $ cd lighttpd-1.4.18/
    $ ./configure
    $ make
    $ sudo cp src/spawn-fcgi /usr/bin/spawn-fcgi  After spawn-fcgi has been copied to the desired location, you can safely remove the build directory and original source file:    $ cd ..
    $ rm -rf lighttpd-1.4.18/
    $ rm lighttpd-1.4.18.tar.bz2

    Run spawn-fcgi

    This part will be fairly distribution-specific, but I’ll provide the basic command that you’ll need. What you want to do is find a way to run this command as part of your init scripts so the processes will be spawned automatically when you reboot your server.

    /usr/bin/spawn-fcgi -f /usr/bin/php-cgi -a 127.0.0.1 -p 53217 -P /var/run/fastcgi-php.pid

    • -f → the filename of the fcgi-application; in our case we want “php-cgi”, which is provided by your distribution’s PHP package. If you don’t know where to find it, try running which php-cgi on the command line.
    • -a → the IP address to bind the processes to; in our case we want the localhost
    • -p → the port number to bind the processes to; pick whatever you want that won’t cause a conflict (technically it would be best to pick a random number between 49152 and 65535), just make sure to remember the number and use that same port for your Nginx configuration file later on
    • -P → the location where to save the process id file; you can use this file to easily kill the processes later

    For better security, you can also spawn the processes as a non-privileged user by specifying the user/group with the -u and -g flags respectively. For more information on all the available options, run spawn-fcgi -h on the command line.

    If you’re interested in seeing the complete init script that I wrote for use with Arch Linux, you can download it here: fastcgi-php

    Step Two: Complete 83.33% of the Famous 5-Minute Install

    Next you should download the WordPress files and extract them to their final location on your server. Simply follow steps 1–5 of the Famous 5-Minute Install (the 6th and final step requires that your web server be up and running properly, so we’ll do it later). This guide will assume that you extracted the WordPress core files here: /srv/www/nginx/domain.com/

    Step Three: Nginx Configuration

    To get the web server up and running properly, the file you need to edit is called “nginx.conf” and is installed in different places depending on your Linux distribution. If you install Nginx from source, the default location is /usr/local/nginx/conf/nginx.conf, however yours may be somewhere else.

    Once you find that file, open it with your favorite text editor and add a server declaration that looks something like this (I’ll cover what each part means after posting the code):

    server {
        listen       12.34.56.78:80;  # your server's public IP address
        server_name  domain.com;      # your domain name
    
        location / {
            root   /srv/www/nginx/domain.com;  # absolute path to your WordPress installation
            index  index.php index.html index.htm;
    
            # this serves static files that exist without running other rewrite tests
            if (-f $request_filename) {
                expires 30d;
                break;
            }
    
            # this sends all non-existing file or directory requests to index.php
            if (!-e $request_filename) {
                rewrite ^(.+)$ /index.php?q=$1 last;
            }
        }
    
        location ~ \.php$ {
            fastcgi_pass   localhost:53217;  # port where FastCGI processes were spawned
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME    /srv/www/nginx/domain.com$fastcgi_script_name;  # same path as above
    
            fastcgi_param  QUERY_STRING       $query_string;
            fastcgi_param  REQUEST_METHOD     $request_method;
            fastcgi_param  CONTENT_TYPE       $content_type;
            fastcgi_param  CONTENT_LENGTH     $content_length;
    
            fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
            fastcgi_param  REQUEST_URI        $request_uri;
            fastcgi_param  DOCUMENT_URI       $document_uri;
            fastcgi_param  DOCUMENT_ROOT      $document_root;
            fastcgi_param  SERVER_PROTOCOL    $server_protocol;
    
            fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
            fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;
    
            fastcgi_param  REMOTE_ADDR        $remote_addr;
            fastcgi_param  REMOTE_PORT        $remote_port;
            fastcgi_param  SERVER_ADDR        $server_addr;
            fastcgi_param  SERVER_PORT        $server_port;
            fastcgi_param  SERVER_NAME        $server_name;
    
            # required if PHP was built with --enable-force-cgi-redirect
            fastcgi_param  REDIRECT_STATUS    200;
        } }

    You will need to edit all of the highlighted sections above using your own information. The first part is merely the server declaration where you define what your server’s publicly available IP address is and what domain name that address is associated with.

    Next we add to that some default settings for the root location. The key part here is that WordPress uses the “Front Controller” design pattern, meaning that any request for a file that does not exist on the server should be handled by the main index.php file. To do this, we need an appropriate set of rewrite rules pointing to the proper path of our installation.

    Last, we add one more location block that tells Nginx to dynamically forward PHP requests to the FastCGI processes we spawned earlier. That’s it!

    Step Four: Finishing Up

    Everything should be good to go…all you need to do now is start your Nginx server process (another distribution specific command), then complete the 6th step of the Famous 5-Minute Install and you should have WordPress up and running on Nginx!

    
    
    
    
    

    Quoted from elasticdog.com