Friday, September 11, 2015

Nginx web server with Varnish cache

First let us understand about Nginx and Varnish:

Nginx (pronounced "engine x") is a web server with a strong focus on high concurrency, performance and low memory usage. It can also act as a reverse proxy server for HTTPHTTPSSMTPPOP3, and IMAP protocols, as well as a load balancer and an HTTP cache.
Nginx can be deployed to serve dynamic HTTP content on the network using FastCGI, SCGI handlers for scripts, WSGI application servers or Phusion Passenger module, and it can serve as a software load balancer.
Nginx uses an asynchronous event-driven approach to handling requests, instead of the Apache HTTP Server model that defaults to athreaded or process-oriented approach, where the Event MPM is required for asynchronous processing. Nginx's modular event-driven architecture can provide more predictable performance under high loads.

Varnish Cache is a web application accelerator also known as a caching HTTP reverse proxy. You install it in front of any server that speaks HTTP and configure it to cache the contents. Varnish Cache is really, really fast. It typically speeds up delivery with a factor of 300 - 1000x, depending on your architecture.

Install & configure
Nginx can be installed on MAC using brew.
$brew install nginx
will install Nginx for you.
Then go to /usr/local/etc/nginx/nginx.conf to configure the server and location settings. This is the simplest of the settings.
server {
        listen       8080;
        server_name  localhost;
        location / {
            root   html;
            index  index.html index.htm;
        }
}
Start up Nginx:
bash-3.2$ cd /usr/local/Cellar/nginx/1.8.0/bin
bash-3.2$ nginx
bash-3.2$ ps -ef | grep nginx

Varnish can be installed on MAC using brew.
$brew install varnish
Configure default.vcl file for varnish at /usr/local/Cellar/varnish/4.0.3/etc/varnish
Minimum setting required is:
vcl 4.0;
backend default {
    .host = "127.0.0.1";
    .port = "8080";
}

Startup Varnish with a command like:
bash-3.2$ sudo sbin/varnishd -a :6081 -T localhost:6082 -f etc/varnish/default.vcl -s malloc,512m

Here -a option is where varnish will listen for traffic.
-T is for the admin url
-f to give vcl file


Run Varnish with Nginx

With this setup, request sent to http://localhost:6081/ will hit Varnish, if the requested resource is cached then varnish will return it with HTTP 304 Status code, otherwise it will forward the request to nginx listening at port 8080 and it would return the response with HTTP status 200.
Reference:

  • Nginx - https://en.wikipedia.org/wiki/Nginx
  • Varnish - https://www.varnish-cache.org/about

1 comment: