Cookies setting

Cookies help us enhance your experience on our site by storing information about your preferences and interactions. You can customize your cookie settings by choosing which cookies to allow. Please note that disabling certain cookies might impact the functionality and features of our services, such as personalized content and suggestions. Cookie Policy

Cookie Policy
Essential cookies

These cookies are strictly necessary for the site to work and may not be disabled.

Information
Always enabled
Advertising cookies

Advertising cookies deliver ads relevant to your interests, limit ad frequency, and measure ad effectiveness.

Information
Analytics cookies

Analytics cookies collect information and report website usage statistics without personally identifying individual visitors to Google.

Information
mageplaza.com

Install & Configure Magento 2 Varnish in a few easy steps

Vinh Jacker | 08-03-2021

Install & Configure Magento 2 Varnish Cache in a few easy steps

Caching is a crucial aspect of any website, especially for Magento 2. It reduces page load time, boosts website speed, and enhances the online shopping experience for customers. Magento 2 Varnish is a top-recommended caching solution that outperforms built-in page caching. It optimizes server workload and, combined with Magento 2, effectively boosts sales.

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

Magento 2 Varnish overview

What is Varnish Cache?

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 caching 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 cache 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 the 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.

The Importance of Varnish Cache for Magento 2 Stores

Magento 2 Varnish dramatically enhances online stores by improving speed, user experience, and sales. Here’s why it’s essential:

  • Improved user experience: Varnish reduces page load times, delivering content 10x faster for a smoother and more satisfying browsing experience.
  • Increased Sales and Conversions: Faster page delivery minimizes cart abandonment and boosts transaction success rates, directly impacting sales and conversions.
  • Customizable varnish configuration (VCL): Store owners can tailor caching rules, manage cookies, and optimize user sessions to meet specific store needs.
  • Enhanced SEO: Faster load times improve search engine rankings, driving more organic traffic and enhancing brand reputation.
  • High availability: Multi-layer servers ensure reliability, even during high traffic, maintaining seamless performance under heavy demand.

Requirements for setting up Magento 2 Varnish Cache

  • Version compatibility is key: Ensure your Magento 2 version is compatible with the chosen Varnish version (4.x, 5.x, 6.x, or 7.0).
  • Adhere to instructions: Carefully follow the installation and configuration guides for both Magento 2 and Varnish.
  • Comply with regulations: Understand and follow any specific regulations or best practices related to Varnish caching to optimize performance and avoid issues.

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 the domain name of the application in this field.
  • Determine the Backend Host.
  • The backend port is the Apache server’s port.
  • Define the grace period to know the time when 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 is 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!

Troubleshoot Regular Varnish Cache Problems in Magento 2

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

  • Clear the cache:

If you have any issues with your store’s content after configuring Varnish Cache, you can try 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:

Please go over your server settings thoroughly, 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!

x
    Jacker

    Jacker is the Chief Technology Officer (CTO) at Mageplaza, bringing over 10 years of experience in Magento, Shopify, and other eCommerce platforms. With deep technical expertise, he has led numerous successful projects, optimizing and scaling online stores for global brands. Beyond his work in eCommerce development, he is passionate about running and swimming.



    Related Post

    Website Support
    & Maintenance Services

    Make sure your store is not only in good shape but also thriving with a professional team yet at an affordable price.

    Get Started
    mageplaza services