Install Varnish Cache with Apache on Ubuntu 22.04 | Easy Setup

Posted on

Install Varnish Cache with Apache on Ubuntu 22.04 | Easy Setup

Install Varnish Cache with Apache on Ubuntu 22.04 | Easy Setup

This comprehensive guide, brought to you by Orcacore, will walk you through the process of installing Varnish Cache with Apache on Ubuntu 22.04. Varnish is a powerful, open-source HTTP reverse proxy and caching accelerator designed to significantly improve website performance. It works by storing copies of web pages in memory, serving them directly to visitors when they request the same page again. This process, known as Full Page Cache, dramatically reduces the load on your web server, leading to faster page load times and a better user experience.

Varnish Cache is particularly beneficial for dynamic websites, such as e-commerce platforms, where content is frequently updated. By caching static versions of pages, Varnish ensures that your webshop remains lightning-fast, even during peak traffic periods.

Before we begin, ensure you have the following prerequisites in place:

  • A server running Ubuntu 22.04.
  • A non-root user with sudo privileges. You can set this up by following our guide on the Initial Server Setup with Ubuntu 22.04.
  • Apache web server installed. You can follow the Apache installation instructions within the How to Install LAMP Stack on Ubuntu 22.04 guide.

Now, let’s dive into the installation and configuration process for Install Varnish Cache with Apache on Ubuntu 22.04.

1. Configure Apache For Varnish Cache

First, update your local package index to ensure you have the latest package information:

sudo apt update

By default, Apache listens on port 80. To integrate Varnish effectively, we need to change Apache’s listening port to 8080. This allows Varnish to act as a reverse proxy, intercepting requests on port 80 and forwarding them to Apache on port 8080 if the content isn’t already cached.

Use the following commands to modify the Apache configuration files:

sudo sed -i -e 's/80/8080/g' /etc/apache2/ports.conf
sudo sed -i -e 's/80/8080/g' /etc/apache2/sites-available/*

These commands use the sed utility to replace all instances of "80" with "8080" in the ports.conf file and all files within the sites-available directory.

After making these changes, restart Apache to apply the new configuration:

sudo systemctl restart apache2

To verify that Apache is now listening on port 8080, run the following command:

sudo netstat -pnlt | grep 8080

The output should resemble the following, confirming that Apache is listening on the correct port:

**Output**
tcp6       0      0 :::8080                 :::*                    LISTEN      4059/apache2

With Apache configured, we can now proceed with the Install Varnish Cache with Apache on Ubuntu 22.04.

2. Set up Varnish on Ubuntu 22.04

To install Varnish Cache, we need to add the official Varnish Cache repository to your system. Start by installing the necessary dependencies:

sudo apt install debian-archive-keyring curl gnupg apt-transport-https -y

Next, add the GPG key for the package repository:

curl -fsSL https://packagecloud.io/varnishcache/varnish70/gpgkey | sudo gpg --dearmor -o /etc/apt/trusted.gpg.d/varnish.gpg

Now, add the Varnish Cache repository to your system’s package sources:

sudo tee /etc/apt/sources.list.d/varnishcache_varnish70.list > /dev/null <<EOF
deb https://packagecloud.io/varnishcache/varnish70/ubuntu/ focal main
deb-src https://packagecloud.io/varnishcache/varnish70/ubuntu/ focal main
EOF

To ensure that the Varnish Cache repository has a higher priority than the default Ubuntu package repository, create a preference file:

sudo vi /etc/apt/preferences.d/varnish

Add the following content to the file:

Package: varnish
Pin: origin packagecloud.io
Pin-Priority: 900

Save and close the file. This configuration ensures that the Varnish package from the specified repository is preferred over the default Ubuntu package.

Update your local package index to reflect the changes:

sudo apt update

Finally, install Varnish Cache on Ubuntu 22.04:

sudo apt install varnish -y

With Varnish Cache successfully installed, we can now configure it to work seamlessly with Apache.

3. Configure Varnish Cache on Ubuntu 22.04

First, verify the default address and port configuration in the Varnish configuration file:

sudo vi /etc/varnish/default.vcl

Locate the "backend default" section and ensure it looks like this:

backend default {
    .host = "127.0.0.1";
    .port = "8080";
}

This configuration tells Varnish to forward requests to Apache, which is now listening on port 8080. Save and close the file.

Next, we need to configure Varnish to listen on port 80, the standard HTTP port. To do this, create a directory for custom systemd configuration files:

sudo mkdir /etc/systemd/system/varnish.service.d

Then, create a custom configuration file:

sudo vi /etc/systemd/system/varnish.service.d/customport.conf

Add the following contents to the file:

[Service]
ExecStart=
ExecStart=/usr/sbin/varnishd -a :80 -a localhost:8443,PROXY -p feature=+http2 -f /etc/varnish/default.vcl -s malloc,256m

This configuration overrides the default Varnish startup command, instructing it to listen on port 80. Save and close the file.

To register the changes, reload the systemd daemon:

sudo systemctl daemon-reload

Restart Varnish to apply the new configuration:

sudo systemctl restart varnish

Verify that Varnish is now listening on port 80:

sudo netstat -ltnp | grep ':80'

The output should confirm that Varnish is listening on port 80.

<img decoding="async" width="826" height="133" src="https://bluehoster.info/wp-content/uploads/2022/10/varnish1-1.webp" alt="Check Varnish Listening Port" srcset="https://bluehoster.info/wp-content/uploads/2022/10/varnish1-1.webp 826w, https://bluehoster.info/wp-content/uploads/2022/10/varnish1-1-300x48.webp 300w, https://bluehoster.info/wp-content/uploads/2022/10/varnish1-1-768x124.webp 768w" sizes="(max-width: 826px) 100vw, 826px">

Testing Varnish Cache with Curl

Now, you can test the Varnish Cache using the curl command:

curl -I http://localhost/
<img decoding="async" width="792" height="423" src="https://bluehoster.info/wp-content/uploads/2022/10/varnish2-1.webp" alt="Testing Varnish Cache" srcset="https://bluehoster.info/wp-content/uploads/2022/10/varnish2-1.webp 792w, https://bluehoster.info/wp-content/uploads/2022/10/varnish2-1-300x160.webp 300w, https://bluehoster.info/wp-content/uploads/2022/10/varnish2-1-768x410.webp 768w" sizes="(max-width: 792px) 100vw, 792px">

Look for the following headers in the output: X-Varnish: 2 and Via: 1.1 varnish (Varnish/7.0). These headers indicate that Varnish is successfully caching and serving content.

Conclusion

Congratulations! You have successfully completed the Install Varnish Cache with Apache on Ubuntu 22.04. By following these steps, you’ve configured Varnish to run on port 80, adjusted Apache to listen on port 8080, and verified that Varnish is caching content. This setup will significantly improve your website’s performance and provide a faster, more responsive experience for your visitors.

Don’t forget to follow us on Facebook, Instagram, and YouTube for more helpful guides and tutorials.

You might also find these guides useful:

  • Back up and Restore FileSystem With Timeshift on Ubuntu 22.04
  • How To Install RPM Packages on Ubuntu 22.04
  • Install Varnish Cache with Nginx on Ubuntu 22.04
  • Varnish Cache Setup with Nginx on Debian 12

Alternative Solutions for Caching

While Varnish is a powerful caching solution, alternative methods can achieve similar performance improvements. Here are two different approaches:

1. Nginx as a Reverse Proxy and Caching Server

Nginx, another popular web server, can also function as a reverse proxy and caching server, often offering a more lightweight alternative to Varnish. Instead of relying on Apache for direct content serving, Nginx can be placed in front to handle caching and request routing.

  • Explanation: Nginx can be configured to cache static and dynamic content. It provides features like microcaching (caching content for very short periods, e.g., 1 second) to improve the performance of dynamic websites without serving stale data. Nginx’s caching mechanism is disk-based, which can be beneficial for larger websites with extensive content.

  • Implementation:

    First, configure Nginx as a reverse proxy for Apache (running on port 8080, as in the original setup). Then, enable caching for specific URLs or content types. Here’s a sample Nginx configuration snippet:

    http {
        proxy_cache_path /tmp/nginx_cache levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;
        proxy_cache_key "$scheme$request_method$host$request_uri";
        proxy_cache_valid 200 302 60m;
        proxy_cache_valid 404 1m;
    
        server {
            listen 80;
            server_name example.com;
    
            location / {
                proxy_pass http://localhost:8080;
                proxy_cache my_cache;
                proxy_cache_valid 200 302 60m;
                proxy_cache_valid 404 1m;
                add_header X-Cache-Status $upstream_cache_status; #For debugging
            }
        }
    }

    In this example:

    • proxy_cache_path: Defines the cache location (/tmp/nginx_cache), structure, zone size (my_cache:10m), maximum size (10g), and inactivity timeout (60m).
    • proxy_cache_key: Defines how cache keys are generated.
    • proxy_cache_valid: Sets caching durations for different HTTP response codes.
    • proxy_pass: Forwards requests to the Apache server on port 8080.
    • add_header: Adds an X-Cache-Status header to the response, indicating whether the content was served from the cache (HIT) or the origin server (MISS). This is useful for debugging.

2. Using a Content Delivery Network (CDN)

A CDN is a geographically distributed network of servers that cache and deliver content to users from the server closest to them. This minimizes latency and improves page load times, particularly for users located far from your origin server.

  • Explanation: CDNs are especially effective for static content (images, CSS, JavaScript files), but many CDNs also offer dynamic content acceleration. By distributing your content across multiple servers, a CDN reduces the load on your origin server and provides a more scalable solution than a single-server caching setup.

  • Implementation:

    Implementing a CDN typically involves signing up with a CDN provider (e.g., Cloudflare, Akamai, AWS CloudFront). You then configure your CDN to pull content from your origin server (Apache, in this case). The CDN will automatically cache your content on its edge servers and serve it to users based on their location. Configuration varies depending on the CDN provider. Typically, you’ll need to:

    1. Sign up for a CDN service.
    2. Configure your domain with the CDN (often involves changing DNS records).
    3. Specify the origin server (your Apache server’s IP address or hostname).
    4. Define caching rules (e.g., cache duration, content types to cache).

Both Nginx caching and CDNs offer effective alternatives to Varnish for improving website performance. The best choice depends on your specific needs and infrastructure. For smaller websites with moderate traffic, Nginx caching may be sufficient. For larger websites with global audiences, a CDN provides a more scalable and geographically optimized solution.

Leave a Reply

Your email address will not be published. Required fields are marked *