Install Varnish Cache with Nginx on AlmaLinux 9 | Best Guide

Posted on

Install Varnish Cache with Nginx on AlmaLinux 9 | Best Guide

Install Varnish Cache with Nginx on AlmaLinux 9 | Best Guide

This guide is designed to walk you through the process of installing and configuring Varnish Cache with Nginx on AlmaLinux 9. Varnish Cache is a powerful web application accelerator, often referred to as a caching HTTP reverse proxy. Think of it as a highly efficient middleman positioned between your website visitors (clients) and your web server. Instead of your web server constantly fielding requests for the same content, Varnish intercepts these requests and serves cached copies, significantly reducing server load and improving website performance. This is especially beneficial for websites with high traffic or content that doesn’t change frequently. The goal is to get your Varnish Cache with Nginx on AlmaLinux 9 working seamlessly.

Let’s delve into the detailed steps required to set up Varnish Cache with Nginx on AlmaLinux 9.

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

Once these prerequisites are met, proceed with the following steps:

1. Install Varnish Cache on AlmaLinux 9

First, update your system’s package index to ensure you have the latest package information:

sudo dnf -y update

Next, disable any existing Varnish modules that might be installed:

sudo dnf module disable varnish

Install the EPEL (Extra Packages for Enterprise Linux) repository, which provides additional packages not available in the default AlmaLinux repositories:

# . /etc/os-release
# sudo dnf install https://dl.fedoraproject.org/pub/epel/epel-release-latest-${VERSION_ID%%.*}.noarch.rpm

Now, you need to add the official Varnish Cache repository to your system. Visit the Varnish Downloads page to find the latest release version. Then, use the following command, replacing varnish72 with the appropriate version if necessary:

curl -s https://packagecloud.io/install/repositories/varnishcache/varnish72/script.rpm.sh | sudo bash

Upon successful completion, you should see the following output:

**Output**
The repository is setup! You can now install packages.

Finally, install the Varnish Cache package:

sudo dnf install varnish -y

Manage Varnish Cache Service

After the installation is complete, start and enable the Varnish service to ensure it runs automatically on system boot:

sudo systemctl start varnish
sudo systemctl enable varnish

Verify that the Varnish Cache service is active and running:

sudo systemctl status varnish

The output should resemble the following, confirming that Varnish is running correctly:

[image of Varnish Cache is active and running on AlmaLinux 9]

2. Configure Varnish on AlmaLinux 9

By default, Varnish listens on port 6081. Since Varnish will be acting as a reverse proxy in front of Nginx, we need to change its listening port to 80, the standard HTTP port.

Open the Varnish service file using a text editor (e.g., vi):

sudo vi /usr/lib/systemd/system/varnish.service

Locate the ExecStart line and modify the -a parameter to specify port 80:

...
ExecStart=/usr/sbin/varnishd  -a :**80** 
...

Save the changes and close the file.

Reload the system daemon to apply the updated configuration:

sudo systemctl daemon-reload

3. Configure Nginx to Work with Varnish Cache

Now, configure Nginx to listen on port 8080 instead of the default port 80. This is because Varnish is now handling incoming HTTP requests on port 80.

Open the Nginx configuration file:

sudo vi /etc/nginx/nginx.conf

Within the server block, change the listen directives to port 8080:

server {
listen    **8080** default_server;
listen [::]:**8080** default_server;
.....

Save the changes and close the file.

Restart Nginx to apply the new configuration:

sudo systemctl restart nginx

Open port 8080 in the firewall to allow traffic to reach Nginx:

# sudo firewall-cmd --zone=public --add-port=8080/tcp --permanent
# sudo firewall-cmd --reload

Finally, configure Varnish to use Nginx as its backend server. Edit the Varnish configuration file:

sudo vi /etc/varnish/default.vcl

Locate the backend default block and update the .host and .port directives to point to the Nginx server:

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

4. Testing Varnish Cache

To verify that Varnish Cache is properly configured and working with Nginx, use the curl command to send an HTTP request to your server:

curl -I http://localhost
[Image of Testing Varnish Cache AlmaLinux 9]

This command retrieves the HTTP headers. If you run the command again, you should see an Age header in the response, indicating that the content is being served from the Varnish cache:

curl -I http://localhost
[Image of Testing Varnish Cache with Nginx]

This setup will also work for valid domain names with DNS A records set.

Conclusion

You have now successfully installed and configured Varnish Cache with Nginx on AlmaLinux 9. This configuration significantly enhances website performance by caching content and reducing the load on your web server. Varnish acts as a front-end proxy, serving cached pages to visitors, while Nginx continues to handle other web server functionalities.

Consider exploring these related articles for further optimization and security:

FAQs

<div id="rank-math-faq">
<div id="faq-question-1739790572067">
<h3>Why use Varnish with Nginx?</h3>
<p>Varnish caches static and dynamic content, reducing server load and improving response time, while Nginx handles additional optimizations and SSL termination.</p>
</div>
<div id="faq-question-1739790642865">
<h3>How do I monitor Varnish cache activity?</h3>
<p>You can use the command: <code>varnishstat</code></p>
</div>
<div id="faq-question-1739790653585">
<h3>Can Varnish cache HTTPS traffic?</h3>
<p>No, Varnish does not handle SSL directly. You need to configure Nginx to terminate SSL and pass requests to Varnish.</p>
</div>
</div>

Alternative Solutions for Web Acceleration on AlmaLinux 9

While Varnish Cache is a robust solution for web acceleration, there are alternative approaches you can consider for AlmaLinux 9. Here are two different ways to achieve similar performance improvements:

1. Nginx Microcaching

Nginx itself offers built-in caching capabilities, including microcaching. Microcaching involves caching content for very short periods, typically a few seconds. This approach can significantly reduce server load, especially for dynamic content that changes frequently. Unlike Varnish, it’s configured directly within your Nginx configuration, eliminating the need for an additional service.

Explanation:

Microcaching works by storing responses in Nginx’s shared memory cache. When a request arrives, Nginx checks if a valid cached copy exists. If so, it serves the cached copy directly, bypassing the backend server. After the cache duration expires, the cached copy is refreshed on the next request. This method is simpler to configure than Varnish and can be very effective for reducing server load on dynamic websites.

Code Example:

Add the following directives to your Nginx server block within the nginx.conf file:

http {
    proxy_cache_path /tmp/nginx_cache levels=1:2 keys_zone=microcache:10m max_size=10g inactive=60m use_temp_path=off;
    proxy_cache_key "$scheme$request_method$host$request_uri";
    proxy_cache_valid 200 302 304 1s; # Cache successful responses for 1 second
    proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504;
    proxy_cache_lock on;

    server {
        listen 80;
        server_name yourdomain.com;

        location / {
            proxy_pass http://localhost:8080; # Your backend server
            proxy_cache microcache;
            proxy_cache_bypass $http_upgrade;
            proxy_no_cache $http_upgrade;
        }
    }
}

Explanation of Directives:

  • proxy_cache_path: Defines the cache storage location, memory zone, maximum size, and inactivity timeout.
  • proxy_cache_key: Defines the key used to identify cached responses.
  • proxy_cache_valid: Specifies the cache duration for different HTTP response codes.
  • proxy_cache_use_stale: Allows Nginx to serve stale content when the backend server is unavailable.
  • proxy_cache_lock: Prevents multiple simultaneous requests from trying to update the same cache entry.
  • proxy_pass: Specifies the backend server to which requests are forwarded.
  • proxy_cache: Enables the cache for the specific location.
  • proxy_cache_bypass and proxy_no_cache: Prevent caching for WebSocket upgrades.

Restart Nginx after making these changes:

sudo systemctl restart nginx

2. Content Delivery Network (CDN)

A Content Delivery Network (CDN) is a geographically distributed network of servers that caches content and delivers it to users from the server closest to them. This reduces latency and improves website loading times, especially for users located far from your origin server. Popular CDN providers include Cloudflare, Akamai, and Amazon CloudFront.

Explanation:

When a user requests content from your website, the CDN determines the server closest to the user and serves the cached content from that server. If the content is not yet cached on that server, the CDN retrieves it from your origin server and caches it for future requests. CDNs are particularly effective for serving static assets such as images, CSS, and JavaScript files.

Configuration:

The specific configuration steps vary depending on the CDN provider you choose. However, the general process involves the following:

  1. Sign up for a CDN account.
  2. Configure your CDN to point to your origin server (your AlmaLinux 9 server).
  3. Upload or configure static assets for caching.
  4. Update your website’s DNS records to point to the CDN.

While a specific code example isn’t directly applicable for CDN configuration, consider these Nginx headers for optimal CDN caching, and add them within your server block:

location /static/ { #example for static content folder
    expires 30d; # Cache static assets for 30 days
    add_header Cache-Control "public, max-age=2592000";
    add_header Vary "Accept-Encoding"; # Helps with gzip compression
}

These headers instruct the CDN and browser to cache the content for a specified duration. The Vary header tells the CDN to cache different versions of the content based on the Accept-Encoding header (e.g., gzipped vs. non-gzipped).

These alternative solutions, Nginx microcaching and CDNs, offer viable alternatives to Varnish Cache for improving website performance on AlmaLinux 9, each with its own strengths and trade-offs. Consider your specific needs and technical capabilities when choosing the most appropriate solution.