On this page
- When does Varnish help, and how does the layout work?
- How do you install Varnish?
- How do you bind Varnish to localhost and set the cache size?
- How do you move the site backend to port 8080?
- What does a starter VCL look like?
- How do you set up the public Nginx layer?
- How do you confirm caching and clear it?
- What goes wrong with Varnish most often?
- Questions
When does Varnish help, and how does the layout work?
Varnish helps when many visitors request the same pages and the backend spends time building them, as with a CMS or a shop catalogue. It stores full responses in RAM and serves repeats without touching PHP or the database. It adds little for a static site, which Nginx already serves fast, or for an app where every page is personal to the logged-in user.
Varnish does not speak TLS, so it sits in the middle of three layers on one server:
- Nginx on ports 80 and 443: redirects HTTP, terminates HTTPS and forwards to Varnish.
- Varnish on 127.0.0.1:6081: answers from cache or asks the backend.
- Nginx (or Apache) on 127.0.0.1:8080: the real site, PHP and all.
Only ports 80 and 443 are public. If you are setting up the site layer for the first time, start with the LEMP stack guide.
How do you install Varnish?
On Ubuntu 24.04, 22.04 and Debian 12 or 13 the distribution package is a maintained Varnish release with security fixes. Check what is offered, then install:
sudo apt update
apt policy varnish
sudo apt install -y varnish
varnishd -V
systemctl status varnish --no-pagerThe Varnish project also publishes its own package repository for newer series. Use it only if you need a feature from a later release; the VCL in this guide works on the packaged versions. Varnish sizes its cache from the -s malloc setting, so think about memory now: on a 2 GB server, 256 MB to 512 MB of cache is a sensible start, leaving room for PHP and the database.
How do you bind Varnish to localhost and set the cache size?
Override the service start line so Varnish listens only on the loopback address. First look at the packaged command, because the exact flags vary slightly between releases:
systemctl cat varnish | grep ExecStart
sudo systemctl edit varnishIn the editor, copy the packaged line and change only the -a listen address and the -s size. A typical result:
[Service]
ExecStart=
ExecStart=/usr/sbin/varnishd -j unix,user=vcache -F -a 127.0.0.1:6081 -T localhost:6082 -f /etc/varnish/default.vcl -S /etc/varnish/secret -s malloc,512mThe empty ExecStart= line clears the original before the new one applies. Reload and restart, then confirm the listener:
sudo systemctl daemon-reload
sudo systemctl restart varnish
sudo ss -tlnp | grep varnishdYou should see 127.0.0.1:6081 and the admin port 127.0.0.1:6082.
How do you move the site backend to port 8080?
Change the existing site so it listens on the loopback address and port 8080, and tell it to trust the client address that Varnish forwards. In the site's server block:
server {
listen 127.0.0.1:8080;
server_name example.net;
root /var/www/example.net/public;
index index.php index.html;
set_real_ip_from 127.0.0.1;
real_ip_header X-Forwarded-For;
real_ip_recursive on;
# existing location blocks, PHP handler and so on
}Test with curl -sI -H "Host: example.net" http://127.0.0.1:8080/. A 200 means the backend is ready. If the site uses Apache, change its Listen and VirtualHost port to 8080 the same way and enable mod_remoteip.
What does a starter VCL look like?
Replace /etc/varnish/default.vcl with a short policy: cache anonymous GET requests, pass anything personal, strip cookies from static files and add a header that shows hits.
vcl 4.1;
backend default {
.host = "127.0.0.1";
.port = "8080";
}
acl purgers {
"127.0.0.1";
}
sub vcl_recv {
if (req.method == "PURGE") {
if (!client.ip ~ purgers) { return (synth(405, "Not allowed")); }
return (purge);
}
if (req.method != "GET" && req.method != "HEAD") { return (pass); }
if (req.http.Authorization) { return (pass); }
if (req.url ~ "^/(admin|login|account|cart|checkout|wp-admin|wp-login)") { return (pass); }
if (req.url ~ "\.(css|js|png|jpe?g|gif|svg|webp|ico|woff2?)(\?.*)?$") {
unset req.http.Cookie;
return (hash);
}
if (req.http.Cookie ~ "(session|logged_in|wordpress_logged_in)") { return (pass); }
unset req.http.Cookie;
}
sub vcl_backend_response {
if (bereq.url ~ "\.(css|js|png|jpe?g|gif|svg|webp|ico|woff2?)(\?.*)?$") {
unset beresp.http.Set-Cookie;
set beresp.ttl = 1d;
} elsif (beresp.ttl <= 0s) {
set beresp.ttl = 2m;
}
set beresp.grace = 1h;
}
sub vcl_deliver {
if (obj.hits > 0) { set resp.http.X-Cache = "HIT"; } else { set resp.http.X-Cache = "MISS"; }
}Adjust the pass list and cookie names to your application. A short default TTL of two minutes limits the damage of caching something by mistake while still absorbing traffic spikes. Load the file with sudo systemctl reload varnish; a VCL error leaves the old one running and prints the line number.
How do you set up the public Nginx layer?
Add a public server block that terminates TLS and forwards to Varnish. It also blocks the PURGE method from outside: every request reaches Varnish from 127.0.0.1, so without this line anyone could purge your cache through the proxy.
server {
listen 443 ssl;
listen [::]:443 ssl;
server_name example.net;
ssl_certificate /etc/letsencrypt/live/example.net/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.net/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-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
}
}Keep a port 80 block that only redirects to HTTPS, as in the redirect guide, and get the certificate first with sudo certbot certonly --nginx -d example.net. Then sudo nginx -t && sudo systemctl reload nginx.
How do you confirm caching and clear it?
Request a page twice and compare headers. The second response should say HIT and carry a non-zero Age:
curl -sI https://example.net/ | grep -iE "x-cache|age|x-varnish"
curl -sI https://example.net/ | grep -iE "x-cache|age|x-varnish"
varnishstat -1 -f MAIN.cache_hit -f MAIN.cache_miss
sudo varnishlog -g request -q "ReqURL eq '/'"To clear one URL after publishing, send a purge from the server itself, or ban everything below a path with varnishadm:
curl -X PURGE -H "Host: example.net" http://127.0.0.1:6081/blog/post-1
sudo varnishadm "ban req.http.host == example.net && req.url ~ ^/blog"Many CMS plugins can send purges automatically; point them at 127.0.0.1:6081. Watch memory with the tools in usage monitoring as the cache fills.
What goes wrong with Varnish most often?
- Always MISS: the backend sends
Set-CookieorCache-Control: privateon every page. Find out which withvarnishlogand fix the app or strip the header for anonymous pages. - Logged-in users see each other's pages: the cookie check misses your app's session cookie name. Pass on it explicitly.
- 503 Backend fetch failed: the backend on 8080 is down or slow. Check
curlagainst it and raise.first_byte_timeoutin the backend block for slow pages. - Redirect loop: the app thinks the request is HTTP. Make sure it honours
X-Forwarded-Proto.
Plans that fit this guide
Base city prices. Every plan includes a dedicated IPv4 address, IPv6, full root and all 18 images.
Questions about Varnish cache in front of a site
Does Varnish replace Nginx caching?
Either works for many sites. Nginx proxy_cache is simpler to add; Varnish gives a full language for cache rules, purges, bans and grace mode. Pick Varnish when you need that control.
Will Varnish cache HTTPS?
Varnish itself only sees plain HTTP from Nginx on the same server. Visitors still connect over HTTPS, so the cache works for them transparently.
How much RAM should the cache get?
Enough to hold your popular pages and assets. Start with 256 to 512 MB, watch varnishstat for evictions (n_lru_nuked), and grow only if it climbs.
Is the cache lost on restart?
Yes, the malloc store lives in memory. It refills quickly from normal traffic. A reload of the VCL keeps the cache.
Does this work on Rocky Linux or AlmaLinux?
The concepts are the same, but package names, the service user and SELinux rules differ. This guide covers Ubuntu and Debian.
More in Web servers and proxies
- Install and configure Nginx
- Install and configure Apache
- OpenLiteSpeed web server
- HAProxy load balancer and TLS proxy
- Load balancing with Nginx upstreams
- Nginx as a reverse proxy for an app
- Apache as a reverse proxy
- Compression with gzip and Brotli
- HTTPS and www redirects
- Turn off Apache directory listings
- Nginx Proxy Manager with Docker
- Nginx UI web interface
- Traefik for Docker containers
- Apache Tomcat for Java apps
- Encrypted FTP with vsftpd (FTPS)