All HowTo's Linux Redhat, Fedora and CentOS Linux Web Servers

Varnish Cache as a Load Balancer on CentOS/Redhat

This article explains how to configure the Varnish Cache as a load balancer. In other words, you have two Web Servers with a Varnish server in-front of them. As illustrated below:

Internet -> Varnish -> Web Server 1
                    -> Web Server 2

Varnish does it’s load balancing in a round-robin fashion. It also checks the availability of the Web Servers and discontinues use of any faulty Web Server.

Install Varnish:

yum install varnish

Choose which port you’re going to run Varnish on. Usually this would be TCP port 80. To set this, edit the file “/etc/sysconfig/varnish” and set the following option:

VARNISH_LISTEN_PORT=80

Now edit the “/etc/varnish/default.vcl” file. Comment out the “backend default” section at the top (as in the following example) and replace it with the “backend Server1” and “backend Server2”:

#backend default {
#  .host = "127.0.0.1";
#  .port = "80";
#}

#Specify the first server backend. 
backend Server1 {
  .host = "192.168.0.100";
  .probe = {
                .url = "/";
                .interval = 5s;
                .timeout = 1 s;
                .window = 5;
                .threshold = 3;
  }
}

#Specify the second server backend. 
backend Server2 {
  .host = "192.168.0.101";
  .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.)?company-domain.com$") {
       set req.backend = Pool1;
   }
}

Here is an explanation of what i’ve done above.

Server1 is the first Web Server with IP address 192.168.0.100.
Server2 is the second Web Server with IP address 192.168.0.101.
Pool1 is the name of the balancing pool of Web Servers. 
company-domain.com is the website domain name that you're balancing. 

At this point you should have a working Varnish Cache with Load Balancing.