Varnish Cache in front of Nginx on Ubuntu
Put Varnish in front of nginx on Ubuntu 24.04 or 26.04. Bind it to loopback, write VCL with a health probe and a locked PURGE, then prove each cache hit.
What you are building
Varnish Cache in front of nginx on Ubuntu is an in-memory HTTP cache that answers repeat requests before they reach your site. nginx keeps serving the site on a private loopback port. Varnish listens in front of it and keeps each cacheable response in RAM. The next request for the same URL is served from memory. Both Ubuntu 24.04 and 26.04 ship Varnish in the archive, so you need no third-party repository.
The finished layout has three hops on one server:
- A browser connects to nginx on port 443, which handles TLS (transport layer security).
- nginx forwards the plain HTTP request to Varnish on
127.0.0.1:6081. - Varnish answers from its cache, or fetches the page from a second nginx server block on
127.0.0.1:8080.
The guide builds the two loopback hops first, so you can prove a cache hit with curl before any certificate exists. The TLS front comes last.
Which Varnish version does Ubuntu ship?
Ubuntu 24.04 LTS (long-term support, codename noble) ships Varnish 7.1.1, as package version 7.1.1-1.1ubuntu1. Ubuntu 26.04 LTS (resolute) ships Varnish 7.7.3, as 7.7.3-1build1. Both live in the universe component. As of 10 November 2026, neither release has a newer build in its updates or security pocket, so the version you install is the version the release shipped. The distro pins it for you.
sudo apt update
sudo apt install -y nginx varnish
apt-cache policy varnish
varnishd -Vapt-cache policy shows the installed version and the pocket it came from. If apt reports Unable to locate package varnish, the universe component is disabled on your image. Enable it with sudo add-apt-repository universe and run the install again.
The package starts Varnish as soon as it is installed. Do not leave it that way for long. The stock unit listens on every network interface, and the drop-in step below fixes that.
Move nginx to a backend port
nginx becomes the origin, the server Varnish fetches from. Bind it to loopback on port 8080, so nothing outside the box can reach it directly. Remove the packaged default site, so it does not compete for port 80 later.
sudo mkdir -p /srv/site
echo '<h1>Served through Varnish</h1>' | sudo tee /srv/site/index.html
sudo tee /etc/nginx/sites-available/backend > /dev/null <<'EOF'
server {
listen 127.0.0.1:8080;
server_name _;
root /srv/site;
index index.html;
location = /healthz {
access_log off;
return 200 "ok\n";
}
}
EOF
sudo ln -s /etc/nginx/sites-available/backend /etc/nginx/sites-enabled/backend
sudo rm /etc/nginx/sites-enabled/default
sudo nginx -t && sudo systemctl reload nginx
curl -I http://127.0.0.1:8080/
curl http://127.0.0.1:8080/healthzThe first curl should print a 200 OK status line with a Server: nginx header. The second prints ok. Varnish will poll /healthz to decide whether the backend is alive. If nginx -t fails, nothing was reloaded, and the old configuration is still running.
What does varnish.service start with on your image?
Do not copy the start command from a blog post, this one included. Ask systemd what your package installed:
systemctl cat varnishThe ExecStart= block is the part that matters. In Ubuntu's packaging both releases pass -a :6081 (the listen address), -T localhost:6082 (the management interface), -f /etc/varnish/default.vcl (the VCL file), -S /etc/varnish/secret (the management secret) and -s malloc,256m (a 256 MB memory store). The two releases are not identical. The noble unit adds -j unix,user=vcache. The resolute unit adds -p feature=+http2 instead. Other directives in the unit differ too. Your output is the truth for your server.
Look closely at -a :6081. It has a port and no address, which means Varnish listens on port 6081 on every interface, including the public one. Anyone who finds the port can talk to your cache directly and skip whatever rules the TLS front enforces. The management port is already safe, because localhost:6082 binds to loopback.
Bind Varnish to loopback with a systemd drop-in
Never edit the packaged file under /usr/lib/systemd/system. The next package upgrade replaces it and your change disappears. Put the change in a drop-in file instead. A drop-in that changes ExecStart needs two parts: an empty ExecStart= line first, which resets the list of start commands, and then the full new command. Without the empty line, systemd sees two start commands for a service that may have only one, and refuses to start it.
The two releases start Varnish with different flags. So this command copies the ExecStart block from your own installed unit and changes only the listen address:
unit=$(systemctl show -P FragmentPath varnish)
sudo mkdir -p /etc/systemd/system/varnish.service.d
{
echo '[Service]'
echo 'ExecStart='
sed -n '/^ExecStart=/,/[^\\]$/p' "$unit" | sed 's/-a :6081/-a 127.0.0.1:6081/'
} | sudo tee /etc/systemd/system/varnish.service.d/override.conf
sudo systemctl daemon-reload
sudo systemctl restart varnish
for i in $(seq 1 30); do sudo ss -ltnH 'sport = :6081' | grep -q . && break; sleep 1; doneThe first sed prints from the ExecStart= line to the first line that does not end in a backslash, which is the whole multi-line command. The second sed rewrites the address. tee prints the result, so you can read the drop-in before anything uses it. FragmentPath always points at the packaged unit, so running the command a second time gives the same file. systemctl restart can return before Varnish has opened its listening socket, so the last line checks ss once a second, for up to 30 seconds, until port 6081 appears. If you prefer an editor, sudo systemctl edit varnish opens the same override.conf file and reloads systemd when you save.
Now check that systemd merged it, and that the socket moved:
systemctl cat varnish
sudo ss -ltn 'sport = :6081'systemctl cat should list the drop-in after the packaged unit. The ss filter matches the listening port, not a process name, so it finds the socket whichever Varnish process holds it. The local address should show 127.0.0.1:6081, not 0.0.0.0:6081 or *:6081. If only the header line appears, Varnish is not listening, and journalctl -u varnish -n 20 explains why. If the drop-in held only the new ExecStart line, systemctl restart fails and journalctl -u varnish -n 20 explains why.
Write the VCL: backend, probe and pass rules
VCL (Varnish Configuration Language) decides what Varnish caches. Every VCL file must start with its syntax version, and both Ubuntu packages accept 4.0 and 4.1. Replace /etc/varnish/default.vcl with this file:
vcl 4.1;
backend default {
.host = "127.0.0.1";
.port = "8080";
.probe = {
.url = "/healthz";
.timeout = 2s;
.interval = 5s;
.window = 8;
.threshold = 3;
}
}
acl purge {
"localhost";
"127.0.0.1";
"::1";
}
sub vcl_recv {
if (req.method == "PURGE") {
if (!client.ip ~ purge) {
return (synth(405, "Not allowed."));
}
return (purge);
}
if (req.http.Authorization) {
return (pass);
}
if (req.method == "POST") {
return (pass);
}
if (req.http.Cookie ~ "(^|;\s*)sessionid=") {
return (pass);
}
unset req.http.Cookie;
}
sub vcl_backend_response {
if (beresp.status == 200 && !beresp.http.Cache-Control) {
set beresp.ttl = 5m;
}
set beresp.grace = 1h;
}The backend and its probe. The probe requests /healthz every 5 seconds and allows 2 seconds for an answer. Varnish keeps the last 8 results, and the backend counts as healthy while at least 3 of them succeeded. Those timing and window values are the defaults on both packages. They are written out so you can see them and change them. The default .url is /, which is your real home page, so a dedicated health URL keeps probe traffic out of your page logs. When the probe marks the backend sick, a request with nothing in the cache gets a 503 error from Varnish instead of waiting on a dead server.
Your vcl_recv runs first. Varnish appends its built-in VCL after yours. If your sub vcl_recv ends without a return, the built-in logic runs next. That built-in logic passes (sends straight to the backend, uncached) every request that carries an Authorization header or any Cookie header. It also keeps every method other than GET or HEAD away from the cache. The built-in rules would pass Authorization and POST anyway. Writing them out keeps the whole policy readable in one place.
Cookies are where most setups fail. Browsers send every cookie for a site in one Cookie header, for example Cookie: _ga=GA1.2.3; sessionid=abc123. A test such as req.http.Cookie == "sessionid" compares the whole header to one exact string, so it almost never matches. In a VCL that strips cookies afterwards, as this one does, logged-in users then lose their session cookie and get the anonymous page. The ~ operator runs a regular expression instead. (^|;\s*)sessionid= matches the cookie name at the start of the header or after a semicolon, wherever it sits in the list. Replace sessionid with the session cookie name your application really sets. Read it from your browser's developer tools.
Strip what is left. Requests without a session cookie reach unset req.http.Cookie. That removes analytics and consent cookies, so the built-in rule no longer passes the request, and the anonymous page can be cached. The backend never sees those cookies. That is fine for cookies only JavaScript reads. It is wrong for any cookie your server code reads, so add those names to the pass rule.
The cache key. The built-in vcl_hash builds the key from the URL plus the Host header. That is why every proxy in front of Varnish must pass the client's real Host, which the TLS section below covers.
Set TTL and grace in vcl_backend_response
TTL (time to live) is how long an object stays fresh. Varnish lets you set beresp.ttl and beresp.grace only in vcl_backend_response (and vcl_backend_error), because that is where the backend's response exists. Without your code, Varnish takes the TTL from the response's Cache-Control (s-maxage or max-age) or Expires header, and falls back to the default_ttl parameter, which is 2 minutes.
nginx sends no Cache-Control for a static file unless you configure one, so the rule above gives plain 200 responses 5 minutes. A backend that does send Cache-Control keeps control of its own TTL. Responses with other status codes keep the default TTL.
Grace is the time Varnish may keep serving an expired object while it fetches a new copy in the background. With a 5 minute TTL and 1 hour of grace, the first visitor after expiry gets the stale copy at once, and Varnish refreshes it behind that visitor. The default grace is the default_grace parameter, 10 seconds, unless the backend sends stale-while-revalidate. The long grace also covers outages. The Varnish documentation says that when the backend is sick, the long grace is used, so objects still inside their grace period keep being served.
The built-in logic still runs after yours. A response with a Set-Cookie header is not cached. Varnish stores a hit-for-miss marker instead, so the next requests go to the backend.
Check the VCL with varnishd -C before you reload
varnishd -C compiles a VCL file to C and exits. It never touches the running cache.
sudo varnishd -C -f /etc/varnish/default.vcl 2>&1 | tail -n 5
sudo systemctl reload varnishA valid file ends in lines of generated C code. A broken file prints the compiler's message instead, which names the problem. Fix it before you reload.
The reload itself is fairly safe. The packaged ExecReload runs Ubuntu's varnishreload script, which loads the new VCL with varnishadm vcl.load and switches to it with vcl.use only if the load succeeded. A failed load stops the script, systemctl reload reports the failure, and the old VCL keeps serving. The real danger is the next restart or reboot. On start, Varnish must compile default.vcl, and a broken file means no cache at all. The compile check catches that while you are still logged in.
How do you prove a cache hit?
Send the same request twice, with a short pause between them:
curl -sI http://127.0.0.1:6081/
sleep 2
curl -sI http://127.0.0.1:6081/Compare two headers in the two responses. Age is how long, in seconds, the object has been in the cache. The first response is a miss, so its Age is 0. The second should show an Age of 1 or more, because the pause put two seconds between the store and the hit. X-Varnish holds the transaction ID (VXID) of the request. Compare the value in each response against the log below.
The log is the stronger proof. -d processes what is already in the log and exits, -g request groups each request with its backend fetch, and -q filters by URL:
sudo varnishlog -d -g request -q 'ReqURL eq "/"'The first request shows VCL_call MISS and a backend transaction underneath it, which is the fetch from nginx. The second shows VCL_call HIT followed by VCL_call DELIVER, with no backend transaction at all. That missing fetch is the whole point of the cache.
The counters tell the same story across all traffic. varnishstat -1 prints the statistics once instead of opening the live screen:
sudo varnishstat -1 | grep -E 'MAIN\.cache_(hit|miss) 'cache_hit counts objects delivered without a backend fetch. cache_miss counts objects fetched from the backend first. After the two curl calls above, each should have gone up by one.
Now prove the pass rule and the purge:
curl -sI -H 'Cookie: _ga=1; sessionid=abc' http://127.0.0.1:6081/
sudo varnishlog -d -g request -q 'ReqHeader ~ "sessionid"' -i VCL_call,VCL_return
curl -s -X PURGE http://127.0.0.1:6081/ -o /dev/null -w '%{http_code}\n'
curl -sI http://127.0.0.1:6081/The log for the cookie request should show VCL_return pass right after VCL_call RECV. The PURGE comes from 127.0.0.1, which is in the ACL (access control list), so Varnish removes the object and every stored variant of it. The curl -sI after it is a miss again, with Age: 0. Purging removes one URL. A ban is the other tool: a filter that matches many cached objects, for example everything under one path. Neither one stops new content from being cached.
Put TLS in front: the nginx, Varnish, nginx sandwich
The Ubuntu 7.1.1 and 7.7.3 packages do not terminate TLS. Their -a option accepts only HTTP and the PROXY protocol. Native TLS arrived in Varnish 9, which neither LTS ships. So nginx handles HTTPS on port 443 and hands plain HTTP to Varnish on loopback. Get a certificate first, using Certbot with the nginx plugin on Ubuntu 24.04, then write /etc/nginx/sites-available/front:
server {
listen 80;
listen [::]:80;
server_name example.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
listen [::]:443 ssl;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
if ($request_method = PURGE) {
return 405;
}
location / {
proxy_pass http://127.0.0.1:6081;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
}
}Link it into sites-enabled, run sudo nginx -t, and reload nginx.
Each line in the location block has a reason. By default nginx does not pass the client's Host header upstream. It sends $proxy_host instead, here 127.0.0.1:6081. Varnish puts Host in the cache key, and the origin uses it to pick a server block, so proxy_set_header Host $host keeps both correct. X-Forwarded-Proto carries the original scheme past Varnish to the origin, which talks plain HTTP. An application that builds absolute URLs or forces HTTPS reads that header. Without it the app thinks the request was plain HTTP, and it can send the browser into a redirect loop. The nginx reverse proxy configuration guide explains the rest of the proxy_* directives.
The if block is not optional. Every request that arrives through the front reaches Varnish from 127.0.0.1, because nginx opened that connection. Varnish's client.ip is therefore always loopback, which passes the purge ACL. Without the 405 at the front, anyone on the internet could purge your cache through port 443. The same mechanism is why the origin logs show 127.0.0.1 for every visitor.
Ubuntu's nginx packages (1.24 on noble, 1.28 on resolute) speak HTTP/1.0 to an upstream unless you set proxy_http_version 1.1. Newer upstream nginx releases changed that default, so do not trust current upstream documentation for this one setting. Varnish accepts HTTP/1.0, so the block works as written.
The port 80 block redirects to HTTPS before anything reaches Varnish, so every cached object was stored for an HTTPS request. If you ever let plain HTTP reach Varnish too, and your application answers differently for each scheme, add the scheme to the cache key:
sub vcl_hash {
hash_data(req.http.X-Forwarded-Proto);
}Your vcl_hash has no return, so the built-in one still adds the URL and the host after it. If you are still choosing a front proxy, nginx, Caddy and Traefik compared as reverse proxies covers the trade-offs. The sandwich works the same way with any of them.
How big should -s malloc be on a small VPS?
The packaged unit gives Varnish a 256 MB malloc store. That number is not a limit on the whole process. The size caps the memory used for cached objects. Varnish needs about 1 KB more per object outside that store, and the Varnish documentation warns that the memory the allocator really uses can be substantially higher than the configured size. Plan headroom above the number you set.
On a 1 GB VPS that also runs PHP-FPM and a database, 256 MB is already a large share. Each PHP worker needs its own memory too, and sizing a PHP-FPM pool on a small VPS shows how to count it. When RAM runs out, the kernel kills a process to free memory, and a large Varnish store makes Varnish a likely target.
Measure before you raise it:
sudo varnishstat -1 | grep -E 'MAIN\.n_lru_nuked '
systemctl status varnish --no-pager | grep -i memoryn_lru_nuked counts objects evicted to make room for new ones. If it stays at 0, the cache is not full, and a larger store buys nothing. If it climbs steadily and the hit rate is poor, the working set does not fit, and more memory may help. To change the size, edit the drop-in:
sudo sed -i 's/-s malloc,256m/-s malloc,512m/' /etc/systemd/system/varnish.service.d/override.conf
sudo systemctl daemon-reload
sudo systemctl restart varnishA restart empties the cache, because malloc storage lives only in RAM. Do it at a quiet hour.
Keeping the package patched
Varnish is in universe. Ubuntu's standard security maintenance covers the main component for 5 years: until May 2029 for 24.04 and May 2031 for 26.04. Ubuntu Pro extends coverage to the whole archive, main and universe, for 10 years. Pro is free for personal use on up to 5 machines. Before you put Varnish on a public site, look up the package at ubuntu.com/security/cves and read any open entries for your release. Then keep apt upgrade running on schedule, like any other package.
When is Varnish not worth it?
Varnish only helps when many visitors receive the same bytes for the same URL.
- Logged-in WordPress and similar sites. Every logged-in request carries a session cookie, the pass rule sends it to the backend, and Varnish adds one hop and nothing else. For these users, a Redis object cache for WordPress helps more, because it caches database query results, not whole pages.
- Per-user pages. Dashboards and carts differ for every visitor, so there is nothing to share.
- nginx already caches the page.
fastcgi_cacheis off by default, but once enabled it stores PHP output inside nginx itself. A second full-page cache in front of it adds memory use and another place to purge. - A CDN (content delivery network) already caches at the edge. If the CDN serves most repeat requests, Varnish sees little repeat traffic and has little to do.
Varnish earns its place on a site with mostly anonymous traffic and a slow application behind it.
FAQ
Why does every response from Varnish show Age: 0?
Age: 0 on every request means nothing is being cached, or every request is passed. Run sudo varnishlog -d -g request -q 'ReqURL eq "/"' and read the VCL_return line after VCL_call RECV. pass there means the request carried a cookie your VCL did not strip, or an Authorization header. Methods other than GET or HEAD are never cached either. If the backend response carries a Set-Cookie header, Varnish refuses to store it. A Cache-Control: max-age=0 from the backend also gives a zero TTL.
Why does Varnish return 503 errors after I installed it?
A 503 from Varnish means it could not get a response from the backend. Check that nginx really listens on 127.0.0.1:8080 with sudo ss -ltnp | grep 8080. Then run sudo varnishadm backend.list, which shows whether the health probe marked the backend sick. A probe URL that returns anything other than 200, such as a missing /healthz location, marks a working backend as sick.
Can the Varnish package on Ubuntu serve HTTPS by itself?
No. Varnish 7.1.1 on Ubuntu 24.04 and 7.7.3 on Ubuntu 26.04 accept only HTTP and the PROXY protocol on -a. Native TLS arrived in Varnish 9, which neither LTS ships. Put nginx on port 443 to terminate TLS, proxy to Varnish on loopback, and pass Host and X-Forwarded-Proto so the cache key and the origin both see the real request.
Is it safe to reload Varnish with a VCL file that has an error?
The running cache survives. Ubuntu's varnishreload script loads the new VCL first and switches to it only when the load succeeds, so a broken file leaves the old VCL active and systemctl reload reports a failure. The broken file still sits on disk, though, and the next restart or reboot will fail to start Varnish. Run sudo varnishd -C -f /etc/varnish/default.vcl 2>&1 | tail -n 5 before every reload and read the result.
How much memory should Varnish get on a 1 GB VPS?
Keep the packaged 256 MB, or go lower if PHP-FPM and a database share the box. The configured size covers cached objects only. Varnish needs about 1 KB per object on top, and the allocator can use substantially more than the configured size. Watch n_lru_nuked in varnishstat -1: it stays at 0 while the cache has room, and raising the size only helps once it climbs.