Skip to content

Setting up Varnish in a CentOS server

I've seen Varnish

Varnish is one of those small, shiny, remarcable jewels of the open source world.
It can make an enormous difference in how your web application responds and how fast your web site loads.
It's all in it's caching feature and not only; I've seen people use it as an web application firewall (search github) and out of the box it will only forward well formed HTTP requests to your backend, acting as a filter against malicious activity or scans against your server.
It'll also take the brunt of a syn flood attack, sparing Apache HTTPD or Nginx which usually go belly up quite fast.


Performing an install of Varnish in CentOS 6 is quite trivial as they provide a yum repo:
yum -y install https://repo.varnish-cache.org/redhat/varnish-3.0.el6.rpm
yum install varnish
Out of the box it will listen on port 6081 and will not do much caching. If you want to modify how it works you need to edit 2 files:
/etc/sysconfig/varnish
/etc/varnish/default.vcl
The first file tells Varnish what kind of cache to use and how big, also on which ports to listen to.
The second file configures the backend servers and the way in which the caching is done. Configuring caching in Varnish is not for the faint of heart, so do a serious read-up of the documentation before-hand; there are also many examples online.

Both those files come with working defaults, all you need to do is point your web traffic at it and here you have 2 choices at least:
1 - Assuming Varnish sits on the same IP/machine as the backend, change the port of your web server to something other than 80 (like 8080) and set Varnish to use port 80
2 - Do a redirect from iptables, this is my favourite as it doesn't need any reconfiguration of the web servers:
iptables -t nat -I PREROUTING -i lo -j ACCEPT 
iptables -t nat -I PREROUTING -s LOCAL_IP -p tcp -m tcp --dport 80 -j ACCEPT
iptables -t nat -I PREROUTING -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 6081 

Before you do that, however, you need to tell Varnish which is the backend web server. This is done in /etc/varnish/default.vcl like this:
backend default {
  .host = "LOCAL_IP";
  .port = "80";
}

* LOCAL_IP is your servers IP
You can check the configuration is correct with this command: varnishd -C -f /etc/varnish/default.vcl
Restart Varnish so it's up and running with your configuration: service varnish restart
You can use the commands varnishtop or varnishstat to see what is going on.
Once you do this HTTP traffic will go through Varnish and then to your backend, one consequence of this is that your Apache log will show that all requests are coming from the local IP instead of your visitors' IPs. You can solve that by installing and configuring mod_rpaf.


Enjoy!