Oct 26, 2023 5 min read

Configure Magento 2 to use Varnish on CentOS 7

Configure Magento 2 to use Varnish on CentOS 7 with our step-by-step tutorial. Magento 2 is an open-source e-commerce platform.

Configure Magento 2 to use Varnish on CentOS 7
Table of Contents

Introduction

Before we begin talking about Configuring Magento 2 to use Varnish on CentOS 7, let's briefly understand – What is Magento?

Magento 2 is an open-source e-commerce platform designed for building online stores and marketplaces. It is the successor to Magento 1 and offers a wide range of features and flexibility for creating robust and scalable e-commerce websites.

The success of your online store depends heavily on the page speed or loading time. The overall amount of time it takes for all the content on a given page to load is the loading time. The conversion rate decreases as the loading time increases. It is also among the most significant elements taken into account by Google when determining search engine rankings.

Varnish is an open-source web application accelerator, also known as a caching HTTP reverse proxy. It is designed to significantly improve the performance and scalability of websites by storing copies of dynamically generated web pages in its cache memory. When a user requests a page, Varnish serves the cached version if available, instead of forwarding the request to the web server.

In this tutorial, you will Configure Magento 2 to use Varnish on CentOS 7. We will also address a few FAQs on Configuring Magento 2 to use Varnish on CentOS 7.

Prerequisites

Ensure that you have followed the steps from the first step and enabled the EPEL repository.

How it works

Since Varnish does not support SSL, we must use another server, in this case, Nginx, to act as an SSL Termination Proxy.

When a visitor accesses your website using HTTPS on port 443, the request is handled by Nginx, which acts as a proxy and forwards the request to Varnish (on port 80). Varnish determines whether the request is cached. Varnish will not make a request to the Magento application if it has been cached, and will instead return the cached data to Nginx. Varnish will forward requests that are not cached to Nginx on port 8080, which will retrieve data from Magento, and Varnish will cache the response.

Varnish will redirect users to the HTTPS on port 443 URL if they access your website on port 80 without an SSL certificate.

Configuring Nginx

In order to handle SSL/TLS termination and serve as a backend for Varnish, we need to modify the Nginx server block.

upstream fastcgi_backend {
  server   unix:/run/php-fpm/magento.sock;
}

server {
    listen 127.0.0.1:8080;
    server_name example.com www.example.com;

    set $MAGE_ROOT /opt/magento/public_html;
    set $MAGE_MODE developer; # or production

    include snippets/letsencrypt.conf;
    include /opt/magento/public_html/nginx.conf.sample;
}

server {
    listen 443 ssl http2;
    server_name www.example.com;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/example.com/chain.pem;
    include snippets/ssl.conf;

    return 301 https://example.com$request_uri;
}

server {
    listen 443 ssl http2;
    server_name example.com;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/example.com/chain.pem;
    include snippets/ssl.conf;

    access_log /var/log/nginx/example.com-access.log;
    error_log /var/log/nginx/example.com-error.log;

    location / {
        proxy_pass http://127.0.0.1;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto https;
        proxy_set_header X-Forwarded-Port 443;
    }
}

The default Nginx server block needs to be deleted from the nginx.conf file as well. Comment or remove the lines that follow:

...
# server {
#     listen       80 default_server;
#     listen       [::]:80 default_server;
#     server_name  _;
#     root         /usr/share/nginx/html;
#
#     # Load configuration files for the default server block.
#     include /etc/nginx/default.d/*.conf;
#
#     location / {
#     }
#
#     error_page 404 /404.html;
#        location = /40x.html {
#     }
#
#     error_page 500 502 503 504 /50x.html;
#         location = /50x.html {
#     }
# }
...

In order for modifications to take effect, reload the Nginx service:

sudo systemctl reload nginx

Installing and Configuring Varnish

In order to implement a Full Page Cache for our Magento installation, Varnish, a quick reverse-proxy HTTP accelerator, will sit in front of our web server.

Use the yum command to install Varnish:

sudo yum install varnish

To configure Magento to use Varnish, follow these steps:

php /opt/magento/public_html/bin/magento config:set --scope=default --scope-code=0 system/full_page_cache/caching_application 2

Generating a Varnish configuration file is the next step.

sudo php /opt/magento/public_html/bin/magento varnish:vcl:generate > /etc/varnish/default.vcl

The aforementioned command must be executed as root or a user with sudo privileges, and it will generate a file named /etc/varnish/default.vcl using localhost as the back-end host and port 8080 as the back-end port as default values.

In the default configuration, the health check file's URL is incorrect. Open default.vcl and delete the /pub portion of the line shown in yellow:

...
.probe = {
     # .url = "/pub/health_check.php";
     .url = "/health_check.php";
     .timeout = 2s;
     .interval = 5s;
     .window = 10;
     .threshold = 5;
}
...

Varnish listens on port 6081 by default; we need to change it to port 80:

VARNISH_LISTEN_PORT=80

Start and activate the Varnish service after you have finished making the modifications:

sudo systemctl enable varnish
sudo systemctl start varnish

The varnishlog tool can be used to check present web requests and debug Varnish.

FAQs Configure Magento 2 to use Varnish on CentOS 7

Where can I find the Varnish configuration file for Magento 2? 

The Varnish configuration file for Magento 2 can be found at /etc/varnish/default.vcl. This file contains the settings you can customize to configure Varnish for your Magento 2 installation.

How do I enable Varnish caching in Magento 2? 

To enable Varnish caching in Magento 2, log in to the Magento 2 admin panel and navigate to Stores > Configuration > Advanced > System > Full Page Cache. Change the "Caching Application" option to "Varnish Caching" and save the configuration.

How can I configure Varnish to listen on a different port? 

To configure Varnish to listen on a different port, open the Varnish configuration file (/etc/varnish/default.vcl) and modify the value of the backend default section's .port directive to the desired port number. Save the file and restart Varnish for the changes to take effect.

What is the default TTL (Time To Live) for Varnish cached content in Magento 2?

By default, Varnish cached content in Magento 2 has a TTL of 180 seconds (3 minutes). This means that the cached content will be valid for that duration before Varnish checks with the backend server for updates.

How can I purge the Varnish cache in Magento 2?

To purge the Varnish cache in Magento 2, you can use the command sudo varnishadm "ban req.url ~ /". This command clears the entire Varnish cache and forces Varnish to fetch fresh content from the backend server.

How can I verify if Varnish is properly caching pages in Magento 2? 

To verify if Varnish is caching pages in Magento 2, you can use browser developer tools (such as Chrome DevTools) to check the response headers. Look for the x-varnish header, which indicates that the page was served from Varnish cache.

How can I troubleshoot Varnish-related issues in Magento 2 on CentOS 7? 

If you encounter any Varnish-related issues in Magento 2 on CentOS 7, you can start by checking the Varnish logs located at /var/log/varnish/varnish.log. These logs provide valuable information about cache hits, misses, and backend errors. Additionally, you can review the Varnish configuration file and the Magento 2 configuration settings to ensure they are properly set up.

Conclusion

You now understand how to implement Varnish as a full-page cache to speed up your Magento instance.

If you have any queries, please leave a comment below, and we’ll be happy to respond to them.

Great! You’ve successfully signed up.
Welcome back! You've successfully signed in.
You've successfully subscribed to DevOps Tutorials - VegaStack.
Your link has expired.
Success! Check your email for magic link to sign-in.
Success! Your billing info has been updated.
Your billing was not updated.