About Varnish

Varnish is an HTTP accelerator and a useful tool for speeding up a server, especially during a times when there is high traffic to a site. It works by redirecting visitors to static pages whenever possible and only drawing on the server itself if there is a need for an active process.

Installing Varnish

I assume you already have a web working with nginx. On your terminal, run this command one by one

sudo apt-get install apt-transport-https
curl https://repo.varnish-cache.org/ubuntu/GPG-key.txt | apt-key add -
echo "deb https://repo.varnish-cache.org/ubuntu/ trusty varnish-4.0" >> /etc/apt/sources.list.d/varnish-cache.list
sudo apt-get update
sudo apt-get install varnish

This will install the latest varnish 4 to your system. If you don’t add varnish repo, you’ll only get varnish 3 from official ubuntu repo. Just replace trusty with your version of ubuntu if you don’t use 14.04.

Configuring Varnish

Once you have varnish installed, you can start to configure them to ease the load on your virtual private server.

Varnish will serve the content on port 80, while fetching it from nginx which will run on port 8080.

Go ahead and start setting that up by opening the /etc/default/varnish file:

sudo nano /etc/default/varnish

Find the lines under “DAEMON_OPTS”— in the Alternative 2 section, and change the port number by “-a” to 80. The configuration should match the following code:

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

Next edit the file located at /etc/varnish/default.vcl. Change to port to from 80 to 8080 like below:

backend default {
    .host = "127.0.0.1";
    .port = "8080";
    .connect_timeout = 60s;
    .first_byte_timeout = 60s;
    .between_bytes_timeout = 60s;
    .max_connections = 800;
}

Because this server run Wordpress and Ghost, I need to tell Varnish to not cache the admin area of wordpress and ghost. Still on /etc/varnish/default.vcl I need to modify sub vcl_recv block into this

sub vcl_recv {
        if (!(req.url ~ "wp-(login|admin)")) {
                unset req.http.cookie;
        }

        if (!(req.url ~ "ghost")) {
                unset req.http.cookie;
        }
}

Now the next step would be to edit the port used by nginx. Each server(it you have it configured that way) would need to be switched from 80 to 8080. The location of my config files are /etc/nginx/sites-available.

Once you have made all of the required changes, restart varnish and nginx.

sudo service nginx restart
sudo service varnish restart

Accessing your domain should instantly take you to the varnish cached version. To test, you can run varnishstat, and that should give you live data as you access the domain affected by varnish.