How to set up Varnish and configure it with Apache on Ubuntu 20.04
Varnish is an HTTP accelerator for dynamic web sites with a lot of material. Varnish was created as an HTTP accelerator, unlike other web accelerators such as Squid, which started as a client-side cache, or Apache and nginx, which are essentially origin servers. Unlike other proxy servers that offer FTP, SMTP, and other network protocols, Varnish is solely focused on HTTP.
We need have apache installed before installing Varnish. To install Apache, simply run the following command:
$ sudo apt install apache2
# Varnish should be accessible in the regular Ubuntu repositories for installation. However, before uninstalling it, we must ensure that we are importing the correct and most recent varnish repository. We’ll begin by importing their key:
$ sudo curl http://repo.varnish-cache.org/debian/GPG-key.txt | sudo apt-key add -
After that, we should change the /etc/apt/sources.list file and add the following line:
$ deb http://repo.varnish-cache.org/ubuntu/ lucid varnish-3.0
We must ensure that our repositories are current. Then we’ll be able to install Varnish.
$ sudo apt update
$ sudo apt install varnish
After we’ve installed Varnish, we’ll need to set up some basic configuration parameters. Varnish listens on port 80 by default, so we’ll need to alter Apache’s configuration and tell it to listen on a different port. To change the port on which Apache listens to another port, open the /etc/apache2/ports.conf file and make the following changes:
NameVirtualHost 127.0.0.1:8080
Listen 127.0.0.1:8080
Then, in the default virtual host file (and every other virtual host file that exists), we should make the following changes:
<VirtualHost 127.0.0.1:8080>
To set varnish parameters, enter /etc/default/varnish with your favourite editor and uncomment the following directive:
DAEMON_OPTS="-a :80
-T localhost:6082
-f /etc/varnish/default.vcl
-S /etc/varnish/secret
-s malloc,256m"
In that file, we only need to make those changes. After that, we enter the /etc/varnish/default.vcl file and make the following changes:
backend default {
.host = "127.0.0.1";
.port = "8080";
}
Please keep in mind that 8080 is the Apache listening port. If we want Apache to listen on a different port, we should use that number instead. We’ve completed the initial configuration. The services must then be restarted, and all traffic must now pass through Varnish:
$ sudo service apache2 restart
$ sudo service varnish restart
If we want to verify the current Varnish status, as well as the cached sessions and material served by Varnish, we need use the following command:
# varnishstat
Hitrate ratio: 3 3 3
Hitrate avg: 0.3745 0.3745 0.3745
869844 4.97 2.89 Client connections accepted
31200592 164.04 103.52 Client requests received
11705560 58.66 38.84 Cache hits
Varnish is not caching your pages, and you may start by looking over the documentation for Varnish to see how you might improve your configuration.