All HowTo's Web Servers

Varnish 4 as a Load Balancer

Varnish makes a great load balancer with a very simple configuration process, tolerance features and exceptional caching performance. Things have changed between version 3 and 4 so this article gives an example of how to build a load balancer with Varnish 4.

vcl 4.0;
import std;
import directors;

#Specify the first server backend. 
backend Server1 {
  .host = "10.1.1.2";
  .port = "80";
}

#Specify the second server backend. 
backend Server2 {
  .host = "10.1.1.3";
  .port = "80";
}

sub vcl_init {
     new cluster1 = directors.round_robin();
     cluster1.add_backend(Server1);
     cluster1.add_backend(Server2);
}

# The rule to use the 'pool1' director - the load balancer. 
sub vcl_recv {
   set req.backend_hint = cluster1.backend();
   if (req.url ~ "(?i)\.(jpeg|jpg|png|gif|ico|swf|js|css|gz|rar|txt|bzip)$") {
      unset req.http.Cookie;
      return (hash);
   } else {
      return (pass);
   }
}

Put the above in the “/etc/varnish/default.vcl” file. Check the configuration with the following command:

varnishd -C -f /etc/varnish/default.vcl

If it works (you will get plenty of output) you can then go ahead and start Varnish.

Leave a Reply

Your email address will not be published. Required fields are marked *