The Most Popular Extension Builder for Magento 2

With a big catalog of 224+ extensions for your online store

Install & Configure Magento 2 Varnish in a few easy steps

There are many important factors that make up a valuable website; caching is one of them. It is an essential part of any website. It’s even more urgent for websites running on the Magento 2 platform. Thanks to the advantages of caching, such as reducing page load time, increasing website loading speed, it can bring customers the best experience when shopping online.

One of the top caching techniques that the Magento team highly recommends to users is Magento 2 Varnish. Although each website has a built-in cache for the whole page, it runs very slowly compared to integrating other software. Varnish plays a vital role in managing the cache mechanism, which significantly reduces the workload on the server. Magento 2 and Varnish are a proven combination helping boost sales effectively.

In this blog, let’s explore a step-by-step guide about How to Install & Configure Varnish Cache in Magento 2.

Table of Contents

Magento 2 Varnish overview

What is Varnish Cache?

First of all, let’s take a quick look at the Varnish Cache solution to see what it is specifically?

Varnish Cache, also known as an HTTP accelerator or caching HTTP reverse proxy, is a web application accelerator built on open source code. Varnish Cache can reduce web page response time and network bandwidth consumption for future equivalent requests. Unlike other web servers like Apache or Nginx, Varnish is designed for use with HTTP protocol.

How does Magento Varnish work?

In general, Varnish acts as a catching reverse proxy, sitting between the client and the Magento server. When a user requests a page, Magento 2 Vanish intercepts the request and checks its catche for a cached copy of the page. If a cached copy exists, Varnish serves it directly to the client, eliminating the need to involve the Magento server. This caching mechanism significantly improves response times and reduces the server load.

When Magento 2 Varnish cache doesn’t have a cached copy of the page, it forwards the request to the Magento server. Magento then dynamically generates the requested page by executing the necessary PHP code and retrieving data from the Magento database. Once the response is generated, Magento Varnish caches it for future use, reducing the load on the server for subsequent requests.

Requirements for setting up Magento 2 Varnish Cache

When you set up Magento 2 with Varnish, you have to ensure that you system meets certain requirements, especially the version compatibility. Currently, Magento 2 is compatible with Varnish versions 4.x, 5.x, 6x, and even the varnish 7.0 with Magento lastest version. So, make sure that you have a compatible Magento 2.x version and one of these Varnish versions installed on your server.

Moreover, you need to exactly follow the instructions for use as well as the specific regulations to ensure the best operation of the cache.

How to install Varnish in Magento 2

Despite the fact that Magento has integrated a caching mechanism, it’s not enough. Because of this, Varnish is suggested to apply for every Magento 2 store. To run Varnish on Magento 2, installing Varnish and deploying Varnish Configuration File is urgent.

Please run the following command lines as a root user (sudo su)

apt-get install apt-transport-https
curl https://repo.varnish-cache.org/GPG-key.txt | apt-key add -
echo "deb https://repo.varnish-cache.org/ubuntu/ trusty varnish-4.1" \
     >> /etc/apt/sources.list.d/varnish-cache.list
apt-get update
apt-get install varnish

After that, you will see the Varnish version below if everything is correct.

varnishd -V

Congratulations! You have successfully installed Varnish on Magento 2.

How to configure Varnish Cache in Magento 2

Now, let’s continue with the Magento 2 Varnish configuration

Step 1: Configure your web server

After installing Varnish, you need to configure the current web server. You had better configure your web server to listen on a port 8080 other than the default port 80.

Now it’s time to find your web server and change the listen port to 8080.


 
server {
    listen 8080 default_server;
    server_name your-magento2-store.dev;
    ...
}

Remember that we use port 8080 as an example in this section.

Step 2: Modify Varnish System Configuration

To modify Varnish System Configuration, please open your Varnish Configuration File in a text editor:

/etc/default/varnish

Then, modify the file to get a similar code below:

START=yes
 
# Maximum number of open files (for ulimit -n)
NFILES=131072
 
# Maximum locked memory size (for ulimit -l)
# Used for locking the shared memory log in memory. If you increase log size,
# you need to increase this number as well
MEMLOCK=82000
 
DAEMON_OPTS="-a :80 \
             -T localhost:6082 \
             -p http_resp_hdr_len=64000 \
             -f /etc/varnish/default.vcl \
             -S /etc/varnish/secret \
             -s malloc,256m"

Step 3: Modify default.vcl

  1. First and foremost, you need to backup the old default one:

cp /etc/varnish/default.vcl /etc/varnish/default.vcl.bak

  1. Next, open /etc/varnish/default.vcl in a text editor
  2. Then, modify the lines under ‘backend default’:

# Default backend definition. Set this to point to your content server.
backend default {
.host = "127.0.0.1";
.port = "8080";
}

  1. You need to replace the value of .host with a qualified hostname or IP address as well as the listen port of the Varnish backend or origin server. It’s the server offering the content that Varnish will gain. Commonly, it’s your web server.
  2. You need to replace the value of .port with the listen port (8080) of your web server.

Step 4: Configure Magento to use Varnish

To configure Magento for using Varnish, you need to enable Full Page Cache. Please go to Stores > Configuration > Advanced > System > Full Page Cache, you will see the below image:

Enable Full Page Cache
Enable Full Page Cache

Then, choose Varnish Cache from the Caching Application list.

Caching Application
Caching Application

Next step, you can change the value in TTL for public content field by increasing or decreasing the lifetime value of the public content cache if you want.

TTL for public content
TTL for public content

Afterward, by expanding the Magento 2 Varnish Configuration and entering the following details, you can enable advanced options.

  • Determine the IP or Host that is allowed to delete the Varnish Cache in the “Access list”. Then, please add your domain name of the application in this field.
  • Determine the Backend Host.
  • Backend Port is the port of the Apache server.
  • Define the Grace period to know the time Varnish servers stale content suppose the backend is not responding.

Finally, please click on the Save Config button if you are done. Another way to enable Magento 2 Varnish, you can do it through the command line interface via SSH. If doing this way, please use the following commands:

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

How to Verify Magento 2 Varnish

1. Check suppose Varnish is listening to port 80

To check if Varnish is listening to port 80, please run the command below:

`sudo netstat -tulpn grep varnishd’
Verify Varnish in Magento 2
Verify Varnish in Magento 2

2. Verify your contents in var/cache, var/page_cache folder is not recreated

Once FPC is cleared, cache folders (var/cache, var/page_cache) should be empty because FPC is set up to serve the content from Varnish.

3. Verify the HTTP response headers

To verify the HTTP response headers, you need to load your Magento 2 Frontend and check the response from the browser console. Afterward, you will see a similar screenshot below:

Magento 2 Frontend
Magento 2 Frontend

That’s it. You have completed the Magento 2 Varnish configuration. Let your online store fly!

The Importance of Varnish Cache for Magento 2 Stores

Thanks to the integration of Magento 2 Varnish, customers will no longer have to spend a lot of time and effort waiting for the page load when purchasing or searching for products, leading to numerous benefits that improve your online stores dramatically. If you are still not convinced, some key reasons below will give you a better understanding which advantages Varnish Cache brings to Magento 2 stores.

  • Improve User Experience: By utilizing the cache, the page loading time is significantly reduced and contents showed 10X faster, resulting in a faster and smoother browsing experience, leading to increased satisfaction and improved user experience.

  • Increase Sales and Convension Rates: With Varnish Cache accelerating page delivery, buyers can browse through product listings, view product details, and complete purchases much more efficiently. The improved speed and responsiveness of the website contribute to reduce the chances of cart abandonment and increasing successful transactions. As a result, installing Magento 2 Varnish can have a direct positive impact on Sales and Conversion Rates.

  • Customizable Magento 2 Varnish Configuration Language (VCL): With VCl, store owners have granular control over how Varnish handles incomming and outgoing request. This enable you to define caching rules, manages cookies, handle user sessions, and personalize catching strategies according to your specific requirements. The ability to customize Varnish behavior empowers you to optimize caching and tailor it to your unique Magento store setup.

  • Enhanced Search Engine Optimization (SEO): Search engines priortize websites that offer fast loading times and excellent user experience. By delivering content up to 10 times faster, Varnish Cache helps Magento 2 stores achieve higher reliability, better user engagement, and improved rankings on the Search Engin Results Page (SERP). This, in turn, can drive more organic traffic to the website and enhance brand reputation.

  • High Availability: Magento 2 Varnish offers multi-layer servers that allow you to enable the high availability of a cluster processing solution, even during the periods of high traffic or increased demand.

Troubleshoot Regular Varnish Cache Problems in Magento 2

If you face difficulties with Varnish Cache, consider the following troubleshooting tips:

  • Clear the cache:

If issues arise with your store’s content after configuring Varnish Cache, attempt manual cache clearance. This can be done through the Magento Admin, or alternatively, you can employ the magento cache:clean command via SSH.

  • Check the VCL configuration:

Ensure the correctness and currency of your VCL configuration. Incorrect VCL settings may lead to problems with caching and content delivery.

  • Verify your server settings:

Thoroughly review your server settings, including the backend host and port. Confirm that Varnish Cache establishes correct communication with your web server.

  • Review error logs:

Examine your server’s error logs for any messages or issues associated with Varnish Cache. This practice aids in gaining valuable insights into potential problems and facilitates the identification of solutions.

Frequently Asked Questions

Q1: How to clear or refresh Varnish Cache in Magento 2?

To clear or refresh the cache, you need to use the Admin. Please click SYSTEM -> Tool -> Cache Management -> Flush Magento Cache on the top of the page to refresh. You can also clear or refresh individual cache types.

Q2: How much memory does Varnish Cache need?

256M is the Varnish’s default memory limit. However, if you use Varnish for Full Page Cache, you may need to increase this.

Q3: How much does Varnish Cache cost?

Well, Varnish Cache is an open-source software, so it is available for free. It is released under the 2-clause BSD license, which allows you to use, modify, and distribute Varnish without any licensing fee.

Q4: How fast is Varnish Cache?

Based on your architecture, it often speeds up delivery by a ratio of 300 to 1000.

Final words

To sum up, integrating Varnish Cache in Magento 2 is an ideal solution for your online store if you want to instantly reduce the page load time and increase the page load speed. Thanks to this integration, your website will not only enhance the user experience but also helps boost sales dramatically. Only with some minimal changes can you beautify your online business quickly.

If we have missed any key points related to this topic, or you have any contribution to any documentation for our blog, please feel free to comment below or contact us.

Thank you for reading!

Image Description
Hello, I'm the Chief Technology Officer of Mageplaza, and I am thrilled to share my story with you. My deep love and passion for technology have fueled my journey as a professional coder and an ultra-marathon runner. Over the past decade, I have accumulated extensive experience and honed my expertise in PHP development.

Looking for
Customization & Development Services?

8+ years of experiences in e-commerce & Magento has prepared us for any challenges, so that we can lead you to your success.

Get free consultant
development service
x

    Explore Our Products:

    Subscribe

    Stay in the know

    Get special offers on the latest news from Mageplaza.

    Earn $10 in reward now!

    Earn $10 in reward now!

    comment
    iphone
    go up