If your production environment is fronted by a Varnish caching layer, there’s a good chance
your development environment isn’t. This can introduce a number of unanticipated consequences when deploying new code to your
production environment that interacts with Varnish, so it’s best to have the cache layer also available in your dev environment.
This post will cover the steps required to install and configure Varnish 4 in a local Vagrant environment,
running a vanilla Ubuntu 14.04 install. If you don’t already have a Vagrant box set up, follow the instructions in
their getting started guide.
Setting Varnish up manually
The simplest way to set up the Varnish service is on the Vagrant box directly, so I’ll cover that first.
First you need to install the Varnish GPG key.
Next add the deb package from Varnish.
Finally install the varnish package.
You will see from the * Starting HTTP accelerator varnishd line that the Varnish service has been started.
If you open a web browser and hit your Vagrant box root url on port 6081 you should get a 503 Backend fetch failed
error (assuming your default web app responds on port 80 and not port 8080 - Varnish is set up to hit port 8080 by
default). If you open /etc/varnish/default.vcl you will see the default settings:
Update this file to use the correct port and restart Varnish.
Reload your web browser, and you should see the root page as expected.
There are two quick ways to validate that the requests to your web server are going through Varnish.
The first is by simply inspecting the response headers returned from the request. They should contain the headers
Via:1.1 varnish-v4 and X-Varnish:<id> or X-Varnish: <id> <id-r>. For a cache miss, only the ID of the current
request is returned (<id>), and for a cache hit, both the ID of the current request and the ID of the request that
populated the cache are returned (<id> and <id-r>).
The second is by enabling varnishlog inside your Vagrant box, which is quite verbose but will tell you everything
there is to know about the request.
Setting Varnish up via Chef
To provide this in a rebuildable Vagrant environment, you can add the steps outlined above to your Vagrantfile.