Today I learned: Activating Varnish cache for Magento 2

Today I will do my best to explain how to configure Varnish cache for Magento 2.4.2.

I used the official Docker image for Varnish and built a simple Dockerfile along with a Magento recommended ENV value:

FROM varnish:6.6.0-1
COPY default.vcl /etc/varnish
ENV VARNISH_SIZE=2G

The default.vcl file is provided below:

vcl 4.0;

backend default {
  .host = "webserver";
  .port = "80";
  .first_byte_timeout = 600s;
}

As you can see it’s a very simple configuration for bootstrapping the service. The host in this case is the DNS name of your Magento server(e.g. Apache or NGINX). For this experiment we are “baking” the config into the Dockerfile. Once we have our Magento up and running we may connect to Varnish and access our site.

But to actually use Varnish we will have to configure it in the admin as well as adjust the default.vcl configuration file. So we have to log in into the admin panel. Then access Stores > Settings Configuration > Advanced > System > Full Page Cache. Once you access that page you must select Varnish Cache as the Caching Application. Then in Varnish Configuration you must set your server host and port. Afterwards press Export VCL for Varnish 6. Makes sure to save your changes. Once you download the vcl file we will have to adjust it.

First of all I should mention that starting with Magento 2.4.2 the webroot is supposed to be configured to be the pub folder. This is relevant for configuring Varnish because the base configuration generated by the admin panel includes the pub folder in various paths. The problem is since the content is served from pub, Varnish has no clue whatsoever what pub is. From its point of view it sees only the root. So we must remove all pub references from the file otherwise you will get a 503 error because it can’t access the health_check.php file. So just remove the pub references from the config. For example instead of:

backend default {
    .host = "webserver";
    .port = "80";
    .first_byte_timeout = 600s;
    .probe = {
        .url = "/pub/health_check.php";
        .timeout = 2s;
        .interval = 5s;
        .window = 10;
        .threshold = 5;
   }
}

Write in the following manner:

backend default {
    .host = "webserver";
    .port = "80";
    .first_byte_timeout = 600s;
    .probe = {
        .url = "/health_check.php";
        .timeout = 2s;
        .interval = 5s;
        .window = 10;
        .threshold = 5;
   }
}

Once you do that you should restart Varnish and the site should be available. Thanks for reading.

Leave a comment