Varnish

Posted on Sunday March 13, 2016 / by Eric Potvin

Varnish reduce considerebally server load, especially CPU works. It makes the website load faster because it stores the content in RAM.

Install

It is recommended to install varnish through varnish repository. To do so, you need to get the repository:

sudo curl http://repo.varnish-cache.org/debian/GPG-key.txt | sudo apt-key add -

Then, you need to add the repository to the list of apt sources:

echo "deb http://repo.varnish-cache.org/ubuntu/ lucid varnish-3.0" >> /etc/apt/sources.list

Update the repositories and install it:

sudo apt-get update
sudo apt-get install varnish

Configure Varnish

Varnish will serve the content of the website using the port 80 while getting that information from Apache on port 8080.

In order for varnish to work as mentionned above, you need to open the config file:

sudo vi /etc/default/varnish

Uncomment all of the lines under DAEMON_OPTS --under Alternative 2, and use the following configuration:

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

Now, lets tell varnish to look for the server content.

sudo vi /etc/varnish/default.vcl

Let's tell varnish to get the content on port 8080 (from apache):

backend default {
    .host = "127.0.0.1";
    .port = "8080";
}

Since Apache listens on port 80 by default, we need to change this to 8080 in the ports.conf or the apache2.conf file.

sudo vi /etc/apache2/ports.conf
or
sudo vi /etc/apache2/apache2.conf

Change the port number for both NameVirtualHost and Listen line to port 8080:

NameVirtualHost 127.0.0.1:8080
Listen 127.0.0.1:8080

If you have virtual host, you will have to change them as well:

sudo vi /etc/apache2/sites-available/default

And update the VirtualHost entry:

<VirtualHost 127.0.0.1:8080>

Restart Apache and Varnish

sudo service apache2 restart
sudo service varnish restart

You can now check the stats of varnish using this command:

varnishstat