How to install varnish cache on CentOS 6

What is varnish? It is a web application that is installed in “front” HTTP Server delivering information tens of times faster.

Installing varnish on centos 6.

rpm -ivh http://repo.varnish-cache.org/redhat/varnish-3.0/el6/noarch/varnish-release/varnish-release-3.0-1.el6.noarch.rpm
yum install varnish -y

Varnish configuration

nano /etc/sysconfig/varnish

Here we find four alternative, but I will work with the simplest, alternative no 2

Put the # symbol in front of all lines at all the alternatives less than alternative no 2

Alternative no  2 should look like that:

DAEMON_OPTS="-a :80 \
 -T localhost:6082 \
 -f /etc/varnish/default.vcl \
 -u varnish -g varnish \
 -S /etc/varnish/secret \
 -s malloc,256M"

Now varnish will work on port 80 so later we will change the port that  work apache (default apache is on 80 and we’re going to change in 8080)

You can change 256M (means 256 megaram) with 1G (1 giga ram)

Or if you want to save the cache on disk (not on rams) replace
-s malloc,256M
with
-s file,/var/lib/varnish/varnish_storage.bin,3G

Where 3G means 3 giga on disk

Save file with ctrl+o and exit with ctrl+x

Now edit:

nano /etc/varnish/default.vcl

Replace port 80 with 8080 (here we tell varnish that apache work behind on port 8080)

Replace 127.0.0.1 with server Ip

backend default {
 .host = "server IP";
 .port = "8080";
 }

Depending on server settings instead of server IP can leave 127.0.0.1

At the end of the file add basic configuration (for best configuration start studying).

Configuration is made ​​here https://www.varnish-cache.org/trac/wiki/VCLExampleCacheCookies

 

sub vcl_hash {
    hash_data(req.http.cookie);
}

sub vcl_recv {
    if (req.url ~ "^/images") {
        unset req.http.cookie;
    }
}

sub vcl_fetch {
    if (req.url ~ "^/images") {
        unset beresp.http.set-cookie;
    }
}
sub vcl_recv {
 if (req.url ~ "\.(png|gif|jpg|swf|css|js)$") {
    return(lookup);
 }
}

# strip the cookie before the image is inserted into cache.
sub vcl_fetch {
 if (req.url ~ "\.(png|gif|jpg|swf|css|js)$") {
   unset beresp.http.set-cookie;
 }
}

Save file ctrl+o and exit with ctrl+x

Now configure Apache to work with varnish

nano /etc/httpd/conf/httpd.conf

Replace

Listen 80

with IP server address

Listen xxx.xxx.xxx.xxx:8080

( if doesn’t work with server IP address try with 127.0.0.1 )

Than replace

NameVirtualHost *:80

cu

NameVirtualHost xxx.xxx.xxx.xxx:8080

If you have sites on the server you have to change their ports of 80 in 8080 (here in httpd.conf).

Save and restart httpd

service httpd restart

Restart varnish

service varnish restart

Startup on boot

chkconfig varnish on

Done!

Leave a Reply

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