Introduction
Varnish is an HTTP accelerator specifically designed to boost the performance of content-heavy dynamic websites and APIs. Unlike other web accelerators such as Squid, which started as a client-side cache, or Apache and Nginx, which primarily serve as origin servers, Varnish is built to accelerate HTTP content. It optimizes server performance by caching static content and minimizing load on the origin server, particularly during high traffic periods.
Requirements
To install Varnish, you need a user with sudo privileges and Apache installed on your VPS.
Tutorial on how to create new user and grant him sudo privileges can be found here.
Tutorial on how to install LAMP stack (Apache, MySQL, PHP) can be found here.
Installation
Add the Varnish Repository:
Import the GPG key and add the repository:
sudo curl http://repo.varnish-cache.org/debian/GPG-key.txt | sudo apt-key add -
sudo nano /etc/apt/sources.list
Add this line to the file:
deb http://repo.varnish-cache.org/ubuntu/ lucid varnish-3.0
Save and exit (Ctrl + O, Ctrl + X).
Install Varnish:
sudo apt-get update
sudo apt-get install varnish
Configuration
Configure Varnish:
Set up Varnish to listen on port 80 and fetch content from Apache on port 8080. Edit the Varnish configuration:
sudo nano /etc/default/varnish
Update DAEMON_OPTS
to:
DAEMON_OPTS="-a :80 \
-T localhost:6082 \
-f /etc/varnish/default.vcl \
-S /etc/varnish/secret \
-s malloc,256m"
Save and exit (Ctrl + O, Ctrl + X).
Configure the backend server in Varnish:
sudo nano /etc/varnish/default.vcl
Set the backend configuration to:
backend default {
.host = "127.0.0.1";
.port = "8080";
}
Save and exit (Ctrl + O, Ctrl + X).
Update Apache Configuration:
Change Apache's port to 8080:
sudo nano /etc/apache2/ports.conf
Update NameVirtualHost
and Listen
to:
NameVirtualHost 127.0.0.1:8080
Listen 127.0.0.1:8080
Modify the default virtual host:
sudo nano /etc/apache2/sites-available/default
Update the <VirtualHost>
line to:
<VirtualHost 127.0.0.1:8080>
Save and exit (Ctrl + O, Ctrl + X).
Restart Services:
Apply changes by restarting Apache and Varnish:
sudo service apache2 restart
sudo service varnish restart
Conclusion
Your domain should now serve content via the Varnish cache. Monitor Varnish’s performance using:
varnishstat