Magento 2 Optimization with Varnish Cache: How to Install & Configure

Author

Sofia Kostenko

Date Published

Page load speed is critically important for any online store. It directly impacts user experience, conversion rates, and search engine rankings. As your product catalog and traffic grow, server load increases - raising the risk of slowdowns and crashes. For a fast-growing e-commerce business, speed isn't just about convenience - it's a key competitive advantage.

Magento Performance Without Optimization

Magento is a powerful eCommerce platform, but with large product catalogs and high traffic, it can experience slowdowns without proper optimization.

To address this issue, Magento includes a built-in Full-Page Cache (FPC) mechanism that significantly improves page load speeds. This works by storing fully rendered HTML pages on the server, allowing the system to serve cached content for subsequent requests.

As a result, Magento doesn't need to dynamically regenerate pages each time - avoiding dozens of database queries and PHP script executions. For small stores and startups, this is often sufficient to ensure stable performance and reduce server load.

However, the built-in FPC has several significant limitations that become particularly apparent under high traffic conditions:

  • It creates unnecessary server load, as even cached pages still pass through Magento and PHP processing.
  • Response times remain relatively slow compared to dedicated solutions that can deliver pages orders of magnitude faster.
  • FPC stores cache on disk or in Redis, which is slower and less efficient than RAM-based caching systems.
  • The built-in FPC lacks configuration flexibility, handles dynamic/personalized content poorly, and its cache invalidation process can be both imprecise and resource-intensive.

As the project grows, these limitations become increasingly impactful - eventually reaching a point where transitioning to a more performant and scalable solution becomes necessary.

One such solution is Varnish Cache, an external caching system capable of dramatically improving page load speeds while significantly reducing the load on Magento.

Why Varnish Is the Ultimate Performance Solution for Magento 2

Varnish Cache is a high-performance HTTP accelerator (reverse proxy) specifically designed for in-memory content caching and rapid content delivery. In the Magento ecosystem, it acts as an intermediary layer between clients and the server - processing and fulfilling requests without engaging Magento's core infrastructure. This architecture dramatically reduces response times and offloads network traffic from your origin server.

The fundamental difference between Varnish and built-in FPC lies in their caching architecture: While FPC stores HTML in Redis/on disk and still processes requests through Magento's PHP stack, Varnish keeps cached content in RAM and serves it directly - completely bypassing both the web server and Magento. This delivers significantly faster response times than FPC, even under heavy traffic loads.

Ultimately, Varnish transforms Magento into a faster, more flexible, and truly scalable solution - essential for growing eCommerce businesses. It doesn’t just keep your store ‘running’ but delivers content with near-zero latency, maintaining peak performance even with massive product catalogs and relentless user traffic.

Installing and Configuring Varnish for Magento

Installing Varnish

Varnish can be deployed either on the same server as Magento or on a separate machine.

Since the official documentation recommends using Magento Open Source 2.4.7 with Varnish Cache 7.4, this guide will focus on installing that specific version.

Note: Steps may vary depending on your OS. This example covers Ubuntu. For other systems, refer to the official Varnish documentation.

Installation Methods:

1. Install from Ubuntu Repositories (Not Recommended)

1sudo apt-get update
2sudo apt-get install varnish  

Limitation:

  • Installs the version available in Ubuntu’s default repos (often outdated). 
  • May not be compatible with the latest Magento optimizations.

2. Install from Official Varnish Cache Repo (Recommended)

# Update the package list and install required utilities:

1sudo apt-get update
2sudo apt-get install debian-archive-keyring curl gnupg apt-transport-https

# Add the Varnish 7.4 repository GPG key and save it to the recommended directory:

1curl -fsSL https://packagecloud.io/varnishcache/varnish74/gpgkey | sudo gpg --dearmor -o /etc/apt/keyrings/varnishcache_varnish74-archive-keyring.gpg

# Add the Varnish 7.4 repository GPG key and save it to the recommended directory:

1. /etc/os-release

# Add the Varnish 7.4 repository to apt sources using signed-by with the key from /etc/apt/keyrings:

1echo "deb [signed-by=/etc/apt/keyrings/varnishcache_varnish74-archive-keyring.gpg] https://packagecloud.io/varnishcache/varnish74/$ID/ $VERSION_CODENAME main" | sudo tee /etc/apt/sources.list.d/varnishcache_varnish74.list

# Set package priorities to ensure installations from this repository:

1sudo tee /etc/apt/preferences.d/varnishcache > /dev/null <<-EOF
2Package: varnish varnish-*
3Pin: release o=packagecloud.io/varnishcache/*
4Pin-Priority: 1000
5EOF

# Update package indexes including the new repository:

1sudo apt-get update

# Install Varnish 7.4:

1sudo apt-get install varnish

# Verify the installed Varnish version:

1varnishd -V

Advantages:

  • Guarantees the latest stable version (7.4).
  • Fully compatible with Magento 2.4.7.


Modifying Varnish Startup Parameters

By default, Varnish listens on port 6081, but for Magento integration it should use port 80.

To modify Varnish's listening port, execute the following command:

1sudo systemctl edit --full varnish

This will open an editor containing the service unit file (initially copied from /lib/systemd/system/varnish.service).

Locate the line beginning with ExecStart= and change the port from :6081 to :80.

For example, it should look similar to:

1ExecStart=/usr/sbin/varnishd \
2   -a :80 \
3   -a localhost:8443,PROXY \
4   -p feature=+http2 \
5   -f /etc/varnish/default.vcl \
6   -s malloc,256m

After making changes, save the file and exit the editor.

This will create a modified service file at: /etc/systemd/system/varnish.service


Web Server Reconfiguration

Since Varnish is now listening on port 80, your web server (Apache or Nginx) must be reconfigured to use a different port, such as 8080.

Apache:

1sudo nano /etc/apache2/sites-available/000-default.conf (или /etc/httpd/conf/httpd.conf)

# Replace

listen 80

# with

listen 8080

1# Restart Apache:
2sudo systemctl restart apache2

Nginx:

1sudo nano /etc/nginx/sites-available/default

# Replace

listen 80;

# with

listen 8080;

1# Restart Nginx:
2sudo systemctl restart nginx


Configuring Magento to Use Varnish

Configuring Magento to Use Varnish Navigate in Admin Panel:

  • Go to: Stores → Configuration → Advanced → System → Full Page Cache
  • Select Varnish Cache:  Under Caching Application, choose Varnish Cache
  • Configure Varnish Settings:
    • Access list: (e.g., localhost)
    • Backend Host: (typically localhost)
    • Backend Port: (8080, as per your web server setup)
    • TTL for public content: (e.g., 86400 seconds / 1 day)
    • Grace period: (optional, e.g., 30 seconds)
  • Save & Export VCL:
    • Click Save Config
    • Use the Export VCL button to download the generated VCL file

Configuring Varnish

1. Replace the default VCL file

  • Option 1: Manually overwrite /etc/varnish/default.vcl with the file exported from Magento.
  • Option 2: Generate and apply a new VCL file using the Magento CLI:
1bin/magento varnish:vcl:generate --export-version=7 > /etc/varnish/default.vcl

2. Update the backend configuration

Ensure the backend points to your web server (Apache/Nginx) on port 8080:

1backend default {
2    .host = "127.0.0.1";
3    .port = "8080";
4}

3. Restart Varnish to load the new configuration:

1sudo systemctl daemon-reload
2sudo systemctl restart varnish


Validating the Configuration

1. HTTP Headers Check

Use curl or browser DevTools to inspect these critical headers:

1bash curl -I -v http://your-magento-site.com

Key Headers to Verify: X-Magento-Cache-Debug (should show HIT for cached pages, MISS for uncached)

2. Page Load Time

Pages should load significantly faster.

3. File System Check

The var/page_cache folder should remain empty if Varnish is working correctly.

If files appear here, Magento is still using disk caching (misconfiguration).

Verify with:

1ls -l var/page_cache  # Should show no files


How many hours does Varnish implementation take?

A basic Varnish setup for Magento 2 typically takes 4-8 hours and includes installation, web server port reconfiguration, and standard VCL file setup.

However, implementation time can extend significantly to 2-4 days depending on project complexity:

  • customized modules
  • personalized content caching requirements (such as individual pricing or dynamic blocks)
  • integration with load balancers or CDNs.