This tutorial will show you how to use the Varnish caching proxy on your server.
When you are done with this tutorial, request handling on your server will look like this:
Browser --> Nginx --> Varnish --> Apache --> PHP-FPM
Nginx will still be the public-facing server because Nginx uses an asynchronous event-driven model that makes it more scalable than Varnish. Nginx also supports SSL, HTTP/2, and HTTP/3. So, Varnish will only be used for what it's best at: caching.
First, SSH into your server as the root user and install Varnish:
sudo apt-get install varnish
Now, edit the file /etc/varnish/default.vcl
and change the
backend port from "8080":
backend default { .host = "127.0.0.1"; .port = "8080"; }
to "81":
backend default { .host = "127.0.0.1"; .port = "81"; }
Then, restart Varnish by running the following command as root:
sudo service varnish restart
Now, rename your app's
/etc/nginx-sp/vhosts.d/APPNAME.d/main.conf
file to
main.conf.orig
so that you have a backup.
Next, create a file called main.custom.conf
with the contents:
location / { proxy_pass http://127.0.0.1:6081; }
Restart Nginx by running the following command as root:
sudo service nginx-sp restart
All requests from your site are now being sent by Nginx through Varnish before uncached requests hit Apache.
You can monitor Varnish with the command:
varnishtop
You're not done yet! You've only added Varnish to your stack. Now you need to configure its caching rules by adding .vcl files in the /etc/varnish/ directory.
For more information, see the Varnish VCL documentation.