Last Updated: February 25, 2016
· joegardiner

Automate Varnish Cache Purges

If you installed Varnish from a repo you will have all the Varnish utility commands installed as well. You need to make sure that varnishadm is installed so run the command now.

You need to specify the host and secret file for issuing varnishadm commands. To purge the cache on local host you can use the following command.

varnishadm -T localhost:6082 -S /etc/varnish/secret url.purge .

You can check the port using the netstat command.

netstat -l

Look for an unrecognised TCP command.

Active Internet connections (only servers)
tcp        0      0 localhost:6082              *:*                         LISTEN

Before adding the full command to the crontab to automate the task, run it in your terminal. You should see the command executing correctly without throwing any errors. If a connection error does show, check your port number again with netstat.

If the command ran correctly you can now add it to your crontab. Copy the command then open the crontab editor and set the cron to run every minute (only for this example, every minute would be pointless!). The cron tab entry will look like this.

* * * * * varnishadm -T localhost:6082 -S /etc/varnish/secret url.purge .

You can stop here if you’re accessing a local Varnish. If not and you wish to issue cache purge commands from a remote host then keep reading.

Remote purge commands
In order to allow remote connection you need to edit the Varnish config file on your server. Use whichever text editor you prefer.

vim /etc/varnish/default.vcl

You need to copy and paste the following into the default.vcl file.

 acl purge {
 "server IP";

You need to update the server IP to match the IP of the remote server you will be issuing purge commands from. Write and quit the changes and reload the config.

service varnish reload

Now log in to the server you will be issuing commands from. We’re going to edit the crontab again using the same command as before. The only difference is that we are going to edit the host in the varnishadm command.

So, in the crontab (with your own timing settings) paste the following

varnishadm -T varnish-server-IP:port-from-netstat -S /etc/varnish/secret url.purge .

As you can see we have changed the IP and port to those of the target Varnish server. The rest of the command is the same.