This article shows how to use a Varnish server on a CentOS/Redhat server to load balance and exclude faulty or overloaded backend servers.
Make sure that your Varnish server is able to listen on port 80. This may mean turning off your web server or using different ports.
Install Varnish on the Load balancer:
yum install varnish
Check your version. It can make a difference. We’re using version 2.1:
rpm -qa varnish
We get “varnish-2.1.5-5.el6.x86_64”.
Edit your “/etc/sysconfig/varnish” file to have it listen on port 80:
VARNISH_LISTEN_PORT=80
Make a backup of your “/etc/varnish/default.vcl” file.
cp /etc/varnish/default.vcl /etc/varnish/default.orig
Populate your “default.vcl” file with the following. Make sure to change the “.host =” values to the IP addresses of your backend web servers. Also make sure to change the matching domain name at the bottom to your frontend’s FQDN.
#Specify the first server backend. backend Server1 { .host = "1.1.1.1"; .probe = { .url = "/"; .interval = 5s; .timeout = 1 s; .window = 5; .threshold = 3; } } #Specify the second server backend. backend Server2 { .host = "2.2.2.2"; .probe = { .url = "/"; .interval = 5s; .timeout = 1 s; .window = 5; .threshold = 3; } } # Specify the servers to balance between. I call this group 'pool1'. director Pool1 round-robin { { .backend = Server1; } { .backend = Server2; } } # The rule to use the 'pool1' director - the load balancer. sub vcl_recv { if (req.http.host ~ "^www.example.com$") { set req.backend = Pool1; } }
In my testing i did the following:
1. Started with both backend servers running and visited the "www.example.com" website with my browser. I got one of the backend servers. 2. I turned the web server off on the first backend server and within a few seconds i was shown the second backend server web page. 3. I turned on the web server on the second and turned off the first. I was shown the first backend server page.
Play with the “probe” settings to get the tolerance levels you need:
.url = "/"; .interval = 5s; .timeout = 1 s; .window = 5; .threshold = 3;
Changes to the “/etc/varnish/default.vcl” and “/etc/sysconfig/varnish” require varnish to be restarted or reloaded. You should check your config file for syntax errors using:
varnishd -C -f /etc/varnish/default.vcl
It should give plenty of output suggesting it’s ok. If there are errors, it will be obvious. Restarting Varnish will “flush” the cache so do it sparingly.