RHEL BasedRocky Linux

How To Install Varnish on Rocky Linux 10

Install Varnish on Rocky Linux 10

Varnish Cache serves as a powerful HTTP accelerator that dramatically improves website performance by caching frequently requested content. This comprehensive guide walks through the complete installation process of Varnish on Rocky Linux 10, providing detailed step-by-step instructions for system administrators and DevOps professionals.

Rocky Linux 10 offers exceptional stability and enterprise-grade reliability, making it an ideal platform for deploying Varnish Cache in production environments. By following this tutorial, you’ll establish a robust caching solution that reduces server load and enhances user experience through faster content delivery.

Understanding Varnish Cache

Varnish Cache functions as a reverse proxy that sits between web clients and your backend web server. When users request content, Varnish serves cached responses instead of forwarding every request to the origin server. This mechanism significantly reduces backend server load while delivering lightning-fast response times.

The caching system operates through intelligent content storage, keeping frequently accessed web pages, images, and static resources in memory. Varnish excels in high-traffic scenarios where multiple users request identical content simultaneously. Modern websites benefit tremendously from Varnish implementation, particularly content-heavy applications, e-commerce platforms, and news websites that experience substantial visitor volumes.

Performance advantages include reduced page load times, decreased server resource consumption, improved scalability, and enhanced user satisfaction. Varnish typically achieves cache hit ratios exceeding 80%, meaning eight out of ten requests are served directly from cache without touching the backend server.

The architecture positions Varnish as an intermediary layer, intercepting incoming HTTP requests and making intelligent decisions about content delivery. Current Varnish versions available for Rocky Linux 10 include stable releases that provide comprehensive feature sets for enterprise deployments.

Prerequisites and System Requirements

Before proceeding with Varnish installation, ensure your Rocky Linux 10 system meets essential requirements. Minimum specifications include 2GB RAM, though 4GB or more is recommended for production environments. CPU requirements are modest, but sufficient processing power ensures optimal cache management.

Administrative access through sudo privileges or root account access is mandatory for package installation and system configuration. The installation process modifies system services, network configurations, and security settings that require elevated permissions.

An existing web server installation represents a crucial prerequisite. Varnish works alongside Apache or Nginx, not as a replacement. The web server continues handling dynamic content generation while Varnish manages static content caching and delivery.

Network considerations involve port availability planning. Standard HTTP port 80 should be available, as Varnish typically assumes this port while the backend web server moves to an alternative port like 8080. Firewall configuration must accommodate these port changes.

System backup creation before installation provides essential protection against potential configuration issues. Document current system settings and create recovery points for critical services.

Preparing Rocky Linux 10 for Varnish Installation

System preparation begins with comprehensive package updates. Execute the following command to ensure all existing packages reach current versions:

sudo dnf update -y

Repository configuration may require EPEL repository installation for additional package availability. Install EPEL using this command:

sudo dnf install epel-release -y

Essential dependencies installation ensures smooth Varnish deployment. Install core utilities and plugin support:

sudo dnf install dnf-plugins-core curl wget -y

Firewall preparation involves understanding current configuration and planning port assignments. Check existing firewall status:

sudo firewall-cmd --list-all

SELinux considerations for Rocky Linux 10 require attention to security contexts. Verify SELinux status and prepare for potential policy adjustments:

sestatus

Network interface verification ensures proper connectivity. Confirm network adapter configuration and IP address assignment before proceeding with Varnish installation.

Installing Varnish on Rocky Linux 10

Rocky Linux 10 offers multiple installation methods for Varnish Cache. The default repository method provides the simplest approach using the standard package manager.

Method 1: Default Repository Installation

Install Varnish directly from Rocky Linux repositories:

sudo dnf install varnish -y

This method installs the distribution-packaged version of Varnish, which receives regular security updates through the standard update mechanism.

Method 2: Official Varnish Repository

For the latest Varnish features and versions, add the official Varnish repository. First, add the packagecloud.io repository:

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

Install Varnish from the official repository:

sudo dnf install varnish -y

Version verification confirms successful installation. Check the installed Varnish version:

varnishd -V

Installation troubleshooting addresses common issues. If repository addition fails, verify network connectivity and DNS resolution. Package conflicts may require dependency resolution through manual package management.

GPG key verification ensures package authenticity. The official repository setup automatically handles key verification, but manual verification may be necessary in restricted environments.

Basic Varnish Configuration

Service management represents the first configuration step after successful installation. Start and enable Varnish service for automatic startup:

sudo systemctl start varnish
sudo systemctl enable varnish

Verify service status to confirm proper operation:

sudo systemctl status varnish

Default configuration files reside in /etc/varnish/default.vcl. This Virtual Configuration Language (VCL) file defines caching behavior, backend server settings, and request handling logic.

Port configuration requires modification from the default port 6081 to standard HTTP port 80. Edit the systemd service configuration:

sudo systemctl edit varnish.service

Add the following configuration to override default settings:

[Service]
ExecStart=
ExecStart=/usr/sbin/varnishd -a :80 -T localhost:6082 -f /etc/varnish/default.vcl -S /etc/varnish/secret -s malloc,256m

Memory allocation configuration determines cache storage capacity. The malloc,256m parameter allocates 256MB for cache storage. Adjust this value based on available system memory and expected traffic volume.

Apply configuration changes with daemon reload:

sudo systemctl daemon-reload
sudo systemctl restart varnish

Configuring Web Server Backend

Web server reconfiguration enables Varnish to function as a frontend proxy. The backend server must move from port 80 to an alternative port, typically 8080.

Apache Configuration

Apache port modification involves editing the main configuration file. Open the Apache configuration:

sudo nano /etc/httpd/conf/httpd.conf

Locate the Listen directive and change it from port 80 to port 8080:

Listen 8080

Update virtual host configurations to reflect the port change. Modify any virtual hosts listening on port 80:

<VirtualHost *:8080>
    # Existing virtual host configuration
</VirtualHost>

Restart Apache to apply changes:

sudo systemctl restart httpd

Nginx Configuration

Nginx port configuration requires editing the main configuration file. Open the Nginx configuration:

sudo nano /etc/nginx/nginx.conf

Modify the listen directive in the server block:

server {
    listen 8080;
    # Additional server configuration
}

Restart Nginx service:

sudo systemctl restart nginx

Backend definition in Varnish configuration connects the cache to your web server. Edit the VCL file:

sudo nano /etc/varnish/default.vcl

Configure the backend server:

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

Testing backend connection verifies web server accessibility on the new port:

curl http://localhost:8080

Advanced Varnish Configuration

VCL file customization enables sophisticated caching strategies and request handling. The /etc/varnish/default.vcl file accepts complex configuration rules.

Advanced backend configuration supports multiple servers and load balancing:

backend web1 {
    .host = "192.168.1.10";
    .port = "8080";
    .probe = {
        .url = "/";
        .timeout = 1s;
        .interval = 5s;
        .window = 5;
        .threshold = 3;
    }
}

backend web2 {
    .host = "192.168.1.11";
    .port = "8080";
    .probe = {
        .url = "/";
        .timeout = 1s;
        .interval = 5s;
        .window = 5;
        .threshold = 3;
    }
}

Cache policies and TTL settings control content expiration and refresh behavior. Configure custom cache durations:

sub vcl_backend_response {
    if (bereq.url ~ "\.(js|css|png|gif|jp|jpeg|ico|svg)$") {
        set beresp.ttl = 1h;
    }
    if (bereq.url ~ "\.(html|htm)$") {
        set beresp.ttl = 5m;
    }
}

Performance tuning optimizes memory allocation and cache effectiveness. Adjust storage backend configuration based on available system resources:

sudo systemctl edit varnish.service

Modify memory allocation for high-traffic scenarios:

[Service]
ExecStart=
ExecStart=/usr/sbin/varnishd -a :80 -T localhost:6082 -f /etc/varnish/default.vcl -S /etc/varnish/secret -s malloc,2g

Security considerations involve access control and header management. Implement IP-based restrictions and security headers:

sub vcl_recv {
    if (client.ip !~ "192.168.1.0/24" && client.ip !~ "10.0.0.0/8") {
        return (synth(403, "Forbidden"));
    }
}

SSL/TLS termination with Varnish requires additional configuration or frontend proxy setup. Consider implementing SSL termination at the load balancer level or using Nginx as an SSL proxy.

Firewall Configuration

Firewall rules must accommodate Varnish’s port requirements. Rocky Linux 10 utilizes firewalld for network security management.

Open HTTP port 80 for Varnish access:

sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-port=80/tcp

Backend server port protection ensures the backend remains accessible only to Varnish. Restrict port 8080 access to localhost:

sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="127.0.0.1" port protocol="tcp" port="8080" accept'

Varnish management port (6082) requires protection from external access. This port provides administrative access and should remain restricted:

sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="127.0.0.1" port protocol="tcp" port="6082" accept'

Apply firewall configuration changes:

sudo firewall-cmd --reload

Security best practices recommend minimal port exposure and access restrictions. Regular firewall rule auditing ensures continued security compliance.

Testing port accessibility verifies proper firewall configuration:

sudo ss -tulpn | grep :80
sudo nmap localhost

Testing and Verification

Service status verification confirms Varnish operates correctly after configuration changes:

sudo systemctl status varnish

Port listening confirmation ensures Varnish binds to the correct network interfaces:

sudo netstat -tulpn | grep :80
sudo ss -tulpn | grep varnish

HTTP response testing validates cache functionality using curl commands. Test basic connectivity:

curl -I http://localhost

Cache header verification identifies Varnish responses through specific HTTP headers. Look for cache-related headers:

curl -I http://localhost | grep -E "(Via|X-Varnish|Age)"

Successful Varnish deployment displays headers like:

  • Via: 1.1 varnish
  • X-Varnish: 32768
  • Age: 0 (for fresh content)

Cache hit/miss testing verifies caching behavior. Request the same resource multiple times:

curl -I http://localhost/index.html
curl -I http://localhost/index.html

The second request should show an Age header greater than zero, indicating cache hit behavior.

Performance testing demonstrates caching effectiveness. Use simple load testing tools:

curl -w "@curl-format.txt" -o /dev/null -s "http://localhost/"

Create a curl format file for detailed timing information:

echo "time_namelookup: %{time_namelookup}\ntime_connect: %{time_connect}\ntime_total: %{time_total}" > curl-format.txt

Log analysis provides insights into Varnish operation. Monitor Varnish logs for troubleshooting and performance optimization.

Performance Monitoring and Optimization

Varnish statistics provide comprehensive performance metrics through the varnishstat command. Monitor key performance indicators:

varnishstat

Cache hit ratio analysis determines caching effectiveness. Examine cache hit percentages and identify optimization opportunities. Ideal cache hit ratios exceed 80% for most web applications.

Real-time statistics monitoring enables ongoing performance assessment:

varnishstat -1

Key metrics include:

  • Cache hit ratio
  • Cache misses
  • Backend connections
  • Memory usage

Log analysis tools facilitate detailed request inspection. Use varnishlog for comprehensive request logging:

sudo varnishlog

Filter specific requests or responses:

sudo varnishlog -q "VCL_call eq 'MISS'"

Performance tuning recommendations based on statistics analysis:

  1. Memory allocation optimization: Increase cache memory for higher hit ratios
  2. TTL adjustment: Modify cache duration based on content update frequency
  3. Backend tuning: Optimize backend server performance for cache misses
  4. VCL optimization: Refine caching rules for better content classification

Monitoring best practices include automated alerting for performance degradation and regular performance baseline establishment.

Troubleshooting Common Issues

Service startup problems often relate to configuration errors or port conflicts. Common symptoms include service failure to start or immediate service termination.

Examine systemd service logs:

sudo journalctl -u varnish.service -f

Port binding conflicts occur when multiple services attempt to use the same network port. Identify conflicting services:

sudo lsof -i :80
sudo ss -tulpn | grep :80

Permission and SELinux issues may prevent Varnish from accessing required resources. Check SELinux denials:

sudo ausearch -m AVC -ts recent

Common SELinux solutions involve policy modification or boolean adjustment:

sudo setsebool -P httpd_can_network_connect 1

Backend connection failures indicate communication problems between Varnish and the web server. Verify backend accessibility:

curl http://127.0.0.1:8080
telnet 127.0.0.1 8080

Configuration syntax errors in VCL files prevent Varnish startup. Validate VCL syntax:

sudo varnishd -C -f /etc/varnish/default.vcl

Memory and resource constraints may cause performance degradation or service instability. Monitor system resources:

free -h
df -h
top

Common error resolution strategies:

  1. Service won’t start: Check configuration syntax and port availability
  2. Cache not working: Verify backend connectivity and VCL configuration
  3. Performance issues: Analyze memory allocation and system resources
  4. Access denied errors: Review SELinux policies and file permissions

Security Best Practices

Access control implementation restricts Varnish management interfaces and administrative functions. Limit access to trusted IP addresses and administrative users.

Configure VCL-based access restrictions:

sub vcl_recv {
    if (req.url ~ "^/varnish-status") {
        if (!client.ip ~ "10.0.0.0/8") {
            return (synth(403, "Forbidden"));
        }
    }
}

Regular security updates maintain system security and address known vulnerabilities. Implement automated update procedures:

sudo dnf update varnish

Log management and monitoring enables security event detection and incident response. Configure log rotation and centralized logging:

sudo nano /etc/logrotate.d/varnish

Administrative interface protection secures Varnish management capabilities. Restrict management port access through firewall rules and network segmentation.

Configuration backup strategies ensure rapid recovery from security incidents or configuration errors:

sudo cp /etc/varnish/default.vcl /etc/varnish/default.vcl.backup
sudo tar -czf /backup/varnish-config-$(date +%Y%m%d).tar.gz /etc/varnish/

Security monitoring recommendations include regular vulnerability assessments, access log analysis, and performance anomaly detection.

Congratulations! You have successfully installed Varnish. Thanks for using this tutorial for installing the Varnish HTTP Cache on your Rocky Linux 10 system. For additional help or useful information, we recommend you check the official Varnish website.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button