How to Install Varnish on Ubuntu

Install Varnish on Ubuntu

Installing Varnish on your Ubuntu server can dramatically boost your website’s performance by up to 300 times faster response times. Whether you’re running a high-traffic e-commerce site or a content-heavy blog, Varnish Cache acts like a turbo engine for your web applications. In this comprehensive guide, I’ll walk you through every step of the installation process, from basic setup to advanced configuration.

What is Varnish Cache and Why You Need It

Varnish Cache is a powerful HTTP accelerator that sits between your web server and your users, storing frequently requested content in memory. Think of it as a smart librarian who keeps the most popular books right at the front desk – when someone asks for them, there’s no need to search through the entire library.

Understanding Varnish Cache Performance Benefits

The numbers speak for themselves when it comes to Varnish performance. According to Varnish Software’s benchmarks, properly configured Varnish installations can handle over 20,000 requests per second on modern hardware. This isn’t just theoretical – major websites like The Guardian, Wikipedia, and Vimeo rely on Varnish to serve millions of users daily.

Here’s what makes Varnish so effective:

  • Memory-based storage: Content is served directly from RAM, eliminating disk I/O bottlenecks
  • Smart caching logic: The VCL (Varnish Configuration Language) allows precise control over what gets cached and for how long
  • Built-in load balancing: Distribute traffic across multiple backend servers seamlessly

Real-World Use Cases for Varnish

I’ve seen Varnish transform struggling websites into lightning-fast experiences. E-commerce sites particularly benefit because product pages, which often require database queries, can be served instantly from cache. News websites use Varnish to handle traffic spikes during breaking news events, while API endpoints can serve cached responses for frequently requested data.

Prerequisites for Installing Varnish on Ubuntu

Before we dive into the installation, let’s make sure your system is ready.

System Requirements

You’ll need:

  • Ubuntu 18.04, 20.04, 22.04, or newer
  • At least 1GB of RAM (though 2GB+ is recommended for production)
  • Root or sudo access to your server
  • An active internet connection for downloading packages

Required Permissions and Access

Make sure you can execute sudo commands. If you’re unsure, test with:

sudo whoami

If it returns “root,” you’re all set to proceed.

Method 1: Installing Varnish from Ubuntu Default Repository

The quickest way to get Varnish running is using Ubuntu’s default package repository. While this might not give you the absolute latest version, it’s perfect for getting started quickly.

Quick Installation Steps

First, update your package list to ensure you’re getting the most current package information:

sudo apt update

Now install Varnish with a single command:

sudo apt install varnish

The installation process typically takes 30-60 seconds, depending on your internet connection and system speed.

Verifying the Installation

Let’s confirm everything installed correctly:

varnishd -V

This command displays the Varnish version and build information. You should see output similar to “varnishd (varnish-6.2.1)” followed by additional details.

Check if the service is running:

sudo systemctl status varnish

A green “active (running)” status indicates success.

Method 2: Installing Latest Varnish from Official Repository

For production environments or when you need the latest features, installing from the official Varnish repository is the way to go. This method gives you access to Varnish Cache 6.0 LTS, which includes the most recent performance improvements and security updates.

Adding the Official Varnish Repository

Start by installing the necessary dependencies:

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

These packages enable secure repository management and encrypted downloads.

GPG Key Configuration

Security is crucial when adding external repositories. Import the official Varnish GPG key:

curl -fsSL https://packagecloud.io/varnishcache/varnish60lts/gpgkey | gpg --dearmor | sudo tee /etc/apt/keyrings/varnishcache_varnish60lts-archive-keyring.gpg > /dev/null

This command downloads and installs the cryptographic key that validates package authenticity.

Installing Varnish Cache 6.0 LTS

Now add the repository to your system:

. /etc/os-release
sudo tee /etc/apt/sources.list.d/varnishcache_varnish60lts.list > /dev/null <<-EOF
deb [signed-by=/etc/apt/keyrings/varnishcache_varnish60lts-archive-keyring.gpg] https://packagecloud.io/varnishcache/varnish60lts/$ID/ $VERSION_CODENAME main
EOF

Set package priorities to ensure you get the official version:

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

Update your package list and install Varnish:

sudo apt update
sudo apt install varnish

Configuring Varnish After Installation

Installation is just the beginning. Now we need to configure Varnish to work with your specific setup.

Understanding Varnish Configuration Files

Varnish uses several configuration files, each serving a specific purpose:

Main Configuration Locations

  • /etc/varnish/default.vcl – The main VCL configuration file where you define caching rules
  • /etc/systemd/system/varnish.service – Systemd service configuration
  • /etc/varnish/secret – Management interface authentication file

Basic VCL Configuration

The VCL file is where the magic happens. Here’s a basic configuration that works with most setups:

vcl 4.0;

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

sub vcl_recv {
    # Remove cookies for static content
    if (req.url ~ "\.(css|js|png|gif|jp(e)?g|swf|ico|pdf|flv|mov|mp3|mp4)$") {
        unset req.http.Cookie;
    }
}

This configuration tells Varnish to look for your web server on port 8080 and removes cookies from static files to improve caching effectiveness.

Setting Up Your Web Server Integration

Varnish works as a reverse proxy, so you’ll need to reconfigure your web server to work behind it.

Configuring Apache with Varnish

By default, Apache runs on port 80. With Varnish in front, you’ll move Apache to port 8080. Edit /etc/apache2/ports.conf:

Listen 8080

Update your virtual host configuration to reflect the new port. Don’t forget to restart Apache:

sudo systemctl restart apache2

Nginx Integration Steps

For Nginx users, modify /etc/nginx/sites-available/default:

server {
    listen 8080;
    # rest of your configuration
}

Restart Nginx to apply changes:

sudo systemctl restart nginx

Starting and Managing Varnish Service

Now let’s get Varnish up and running properly.

Systemd Commands for Varnish

Enable Varnish to start automatically at boot:

sudo systemctl enable varnish

Start the service:

sudo systemctl start varnish

For ongoing management, these commands are essential:

  • sudo systemctl restart varnish – Restart the service
  • sudo systemctl reload varnish – Reload VCL configuration without dropping connections
  • sudo systemctl stop varnish – Stop the service

Troubleshooting Common Startup Issues

If Varnish fails to start, check the logs:

sudo journalctl -u varnish -f

Common issues include:

  • Port 80 already in use (solution: ensure your web server moved to port 8080)
  • VCL syntax errors (solution: validate with varnishd -C -f /etc/varnish/default.vcl)
  • Permission problems (solution: verify file ownership and permissions)

Testing Your Varnish Installation

Let’s verify everything is working correctly.

Verification Commands

Check if Varnish is listening on port 80:

sudo netstat -tlnp | grep :80

You should see varnishd in the output.

Test HTTP responses:

curl -I http://your-server-ip

Look for these headers indicating Varnish is working:

  • Via: 1.1 varnish
  • X-Varnish: <numbers>

Performance Testing Tools

Use varnishstat to monitor real-time performance:

varnishstat

This shows cache hits, misses, and other vital statistics. A good cache hit ratio is typically above 80%.

For load testing, try Apache Bench:

ab -n 1000 -c 10 http://your-server-ip/

Optimizing Varnish Performance

Fine-tuning Varnish can squeeze out even more performance.

Memory Configuration

By default, Varnish allocates 256MB for caching. For high-traffic sites, increase this by editing the systemd service file:

sudo systemctl edit varnish

Add these lines:

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

This allocates 1GB for caching. Adjust based on your server’s available RAM.

Cache Storage Options

Varnish offers different storage backends:

  • malloc – Stores cache in RAM (fastest, default)
  • file – Uses disk storage (larger capacity, slower)
  • persistent – Survives restarts (experimental)

For most applications, malloc with adequate RAM provides the best performance.

Common Issues and Troubleshooting

Even the smoothest installations can hit snags. Here are the most common problems and their solutions.

Port Conflicts

If you see “Address already in use” errors:

  1. Check what’s using port 80: sudo lsof -i :80
  2. Stop the conflicting service
  3. Ensure your web server moved to port 8080

Permission Problems

Varnish runs as the varnish user. Configuration files should be readable by this user:

sudo chown -R varnish:varnish /etc/varnish/
sudo chmod 644 /etc/varnish/default.vcl

Security Considerations

Security shouldn’t be an afterthought when deploying Varnish.

Access Control Setup

By default, Varnish’s management interface listens only on localhost. Keep it that way unless you have specific needs. If you must expose it, use strong authentication and firewall rules.

SSL/TLS Configuration

Varnish doesn’t handle SSL/TLS directly. For HTTPS sites, place a SSL terminator (like Nginx or HAProxy) in front of Varnish, or use Varnish behind a load balancer that handles SSL.

Frequently Asked Questions

1. What’s the difference between installing Varnish from Ubuntu’s default repository versus the official Varnish repository?

The Ubuntu default repository typically contains an older, more stable version that’s been thoroughly tested with your Ubuntu release. The official Varnish repository provides the latest version with newest features and performance improvements. For production environments, the official repository is usually preferred for access to Long Term Support (LTS) versions.

2. How much memory should I allocate to Varnish cache?

A good starting point is 25-50% of your available RAM, but never more than 80%. For example, on a 4GB server, allocate 1-2GB to Varnish. Monitor your cache hit ratio and memory usage to fine-tune this setting. More memory generally means better cache performance, but leave enough for your operating system and web server.

3. Can I run Varnish alongside other caching solutions like Redis or Memcached?

Absolutely! Varnish operates at the HTTP level as a reverse proxy, while Redis and Memcached work as application-level caches. Many high-performance setups use multiple caching layers: Varnish for HTTP responses, Redis for database queries, and browser caching for static assets. Each layer serves different purposes and they complement each other well.

4. Why isn’t my Varnish cache working, and how can I troubleshoot it?

Common reasons include: incorrect VCL configuration, cookies preventing caching, cache-busting headers from your application, or Varnish not receiving traffic. Use varnishlog to see real-time requests, varnishstat for cache statistics, and curl -I to check response headers. Look for X-Varnish headers and cache hit/miss indicators in the logs.

5. Is it safe to update Varnish after installation, and how should I do it?

Yes, but always test updates in a staging environment first. Use sudo apt update && sudo apt upgrade for repository installations. Before updating, backup your VCL configuration files and test them with the new version using varnishd -C -f /etc/varnish/default.vcl. For production systems, consider Blue-Green deployment strategies or maintenance windows to minimize downtime.

Marshall Anthony is a professional Linux DevOps writer with a passion for technology and innovation. With over 8 years of experience in the industry, he has become a go-to expert for anyone looking to learn more about Linux.

Related Posts