Andrea Casarin

Andrea Casarin

Published on: 9/11/2022, 8:43:00 AM - Reading time: 1 minute

Nginx caching on Kubernetes

Nginx ingress is one of the best ingress you can use on your K8S cluster, by default it comes with a lot of features but caching is not enabled. Let's see how to set up a simple static cache for our websites.

On cluster ingress (this is managed by an Nginx config map):

proxy_cache_path /tmp/nginx-cache levels=1:2 keys_zone=static-cache:32m max_size=5g inactive=7d use_temp_path=off;
proxy_cache_valid any 5m;
proxy_cache_valid 200 30m;

On application ingress (managed via deploy):

proxy_ignore_headers Set-Cookie;
proxy_cache static-cache;

Watch out for proxy_ignore_headers, these could cache cookies and/or break sessions. You could use something like:

  if ($uri ~ "/admin/") {
    set $app_nocache 1;
  if ($http_cookie ~* "logged_in") {
    set $arg_nocache 1;
  proxy_no_cache $cookie_nocache $arg_nocache $app_nocache;

To avoid caching dynamic pages/admin areas.

And to add a nice touch:

add_header X-Cache-Status $upstream_cache_status;

So that you can watch your response headers to check the cache status for that particular request.