High-Performance Caching with Kubernetes NGINX Ingress and Ghost
Optimize your Ghost CMS on K8s. Learn how to leverage NGINX Ingress for high-performance caching, reducing backend load and improving Time to First Byte (TTFB).
I run my Ghost blog on Kubernetes. It works well for orchestration, but out of the box, it can be heavy on resources. Every page load hits the Node.js backend and the database, even for static posts that haven't changed in months.
The architecture needs to be more efficient. The Ingress layer should handle the heavy lifting by caching content before it ever touches the application.
Configuring the standard Kubernetes NGINX Ingress Controller to do this is harder than it looks. Ghost sends strict Cache-Control: private headers to keep the admin panel secure, and NGINX respects those headers by default.
Here is the production-grade configuration I used to force NGINX to cache public content while keeping the Ghost admin panel secure.
The Architecture
I am using the standard Kubernetes NGINX Ingress Controller. To make caching work, you have to configure two distinct layers:
- The Global Config (ConfigMap): This allocates the disk space for the cache.
- The Ingress Resource: This connects the specific website to that storage and defines the caching rules.
Deploying the Ingress Controller
I deploy the NGINX controller using the official Kubernetes Helm chart. This is the standard way to manage the controller's lifecycle, but the default configuration is too locked down for advanced caching.
To make the global cache configuration persistent, I define the "Fuel Tank" directly in my values.yaml file. This ensures that if I redeploy or upgrade the controller later, I don't lose my cache settings.
Here is the values.yaml configuration I use to unlock the necessary features:
YAML
controller:
# 1. Allow Custom Snippets
# Required to inject our custom caching logic into the Ingress resource
allowSnippetAnnotations: true
config:
# 2. The Global "Fuel Tank" definition
# This injects the cache path directly into the main nginx.conf
http-snippet: |
proxy_cache_path /tmp/nginx-cache levels=1:2 keys_zone=ghost_cache:10m max_size=1g inactive=60m use_temp_path=off;
# 3. Tuning (Optional)
# I lower the risk level to prevent the admission controller from blocking my snippets
annotations-risk-level: Critical
I then deploy or upgrade the controller using Helm:
Bash
helm upgrade --install external-ingress ingress-nginx/ingress-nginx \
--namespace ingress-nginx-external \
--create-namespace \
-f values.yaml
By doing it this way, the proxy_cache_path is initialized immediately when the NGINX pods start, avoiding the "unknown cache zone" errors that happen if you try to apply the Ingress before the storage is ready.
The Global Configuration
Before an Ingress can cache anything, NGINX needs a place to store the files. This must be defined globally in the Controller's ConfigMap.
I also had to enable "snippets" to allow custom NGINX logic injection. The controller blocks these by default for security, so you must explicitly allow them.
The Resulting Configuration:
apiVersion: v1
kind: ConfigMap
metadata:
name: ingress-nginx-controller
namespace: ingress-nginx
data:
# 1. Allow Custom Snippets
allow-snippet-annotations: "true"
# 2. Lower the "Paranoia Level" to allow complex snippets
annotations-risk-level: Critical
# 3. Define the Cache Storage
# Allocates 10MB for keys (RAM) and 1GB for files (Disk)
http-snippet: |
proxy_cache_path /tmp/nginx-cache levels=1:2 keys_zone=ghost_cache:10m max_size=1g inactive=60m use_temp_path=off;
The annotations-risk-level: Critical setting is important here. Without it, the controller’s validation webhook will reject the complex caching logic we are about to write.
ingress-nginx/docs/user-guide/nginx-configuration/configmap.md at main · kubernetes/ingress-nginx Ingress NGINX Controller for Kubernetes. Contribute to kubernetes/ingress-nginx development by creating an account on GitHub. Read more here about annotations-risk-level
The Ingress Configuration
This is where the actual logic lives. I need NGINX to do three things:
- Ignore Ghost's headers: Ghost says "Don't cache this" but I know better for public posts.
- Protect the Admin: I must never cache
/ghost/or logged-in member sessions. - Force the Cache: I use a configuration snippet to inject the cache directive manually. This bypasses the controller's annotation logic which can be flaky.
Here is the complete Ingress YAML:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: ghost-ingress-complete
namespace: ghost
annotations:
# --- Standard Configuration ---
kubernetes.io/ingress.class: "external-nginx"
cert-manager.io/cluster-issuer: letsencrypt-prod
nginx.ingress.kubernetes.io/from-to-www-redirect: "true"
# --- 1. Enable the Engine ---
# NGINX will not cache if buffering is off.
nginx.ingress.kubernetes.io/proxy-buffering: "on"
# --- 2. Use Stale Content (High Availability) ---
# If Ghost crashes, serve the last known good version from cache.
nginx.ingress.kubernetes.io/proxy-cache-use-stale: "error timeout updating http_500 http_502 http_503 http_504"
# --- 3. The Smart Caching Logic ---
nginx.ingress.kubernetes.io/configuration-snippet: |
# A. Force Connection to the "ghost_cache" Zone
proxy_cache ghost_cache;
# B. The Override: Ignore Ghost's "No-Cache" Headers
# This is the critical line that makes caching work.
proxy_ignore_headers Cache-Control Expires Set-Cookie;
# C. Smart Bypass Logic
set $skip_cache 0;
# SAFETY VALVE 1: Never cache the Admin Panel or API
if ($request_uri ~* "/ghost/|/members/|/p/") {
set $skip_cache 1;
}
# SAFETY VALVE 2: Never cache for logged-in members
if ($http_cookie ~* "ghost-members-ssr") {
set $skip_cache 1;
}
# Apply the bypass decisions
proxy_cache_bypass $skip_cache;
proxy_no_cache $skip_cache;
# D. Define Validity
# Cache successful responses for 5 minutes
proxy_cache_valid 200 301 5m;
# Cache 404s for 1 minute (prevents DDoS on missing pages)
proxy_cache_valid 404 1m;
# E. Debug Header (Optional)
add_header X-Cache-Status $upstream_cache_status;
spec:
rules:
- host: www.fracturedarchitecture.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: ghost-service
port:
number: 80
How It Works
The Bypass Logic
The snippet creates a variable $skip_cache initialized to 0 (False). It then checks the request URI. If the user is visiting fracturedarchitecture.com/ghost/ then I set $skip_cache to 1. This instructs NGINX to bypass the cache lookup (proxy_cache_bypass) and refuse to save the result (proxy_no_cache). This ensures the admin panel is always live.
The Ignore Headers Hack
Ghost sends Cache-Control: public, max-age=0 to ensure content freshness. NGINX sees max-age=0 and refuses to cache. The directive proxy_ignore_headers Cache-Control forces NGINX to disregard Ghost's opinion. I then substitute my own rule with proxy_cache_valid 200 5m. This tells NGINX to hold onto the content for 5 minutes.
Handling Memberships and Dynamic Data
You must never cache for logged-in users. If I cache a page for a logged-in user I am taking a snapshot of their personalized view.
If Alice logs in and sees "Welcome Alice", NGINX caches that HTML. When Bob visits the site 10 seconds later NGINX serves him the cached page. Bob now sees "Welcome Alice" and potentially has access to her account details.
This configuration prevents that data leakage using the ghost-members-ssr cookie check. As soon as Ghost identifies a user as a "Member", NGINX steps back and lets Ghost handle every request dynamically.
Safe Caching: Methods and Status Codes
One of the biggest fears with aggressive caching is breaking functionality. What happens when someone posts a comment? What if the WAF blocks a hacker?
This configuration relies on NGINX's strict default behaviors and a "whitelist" approach to status codes to ensure safety.
1. HTTP Methods (Why Forms Still Work)
By default, NGINX acts conservatively. It only caches GET and HEAD requests.
If a user submits a comment (POST), updates their profile (PUT), or deletes a post (DELETE), NGINX automatically bypasses the cache. This means that interactive features, Stripe webhooks, and admin actions pass straight through to the backend without any interference. You don't need to write complex exceptions for every API endpoint; the HTTP protocol handles this distinction for you.
2. WAF Integration (Handling 403 and 444)
My Ingress sits behind a ModSecurity WAF. If a malicious bot attacks the site, the WAF intercepts the request and returns a 403 Forbidden or drops the connection with 444 No Response.
The danger here is Cache Poisoning: If NGINX cached that 403 Forbidden response, legitimate users might visit the homepage and see "Access Denied" because they were served the cached block intended for the hacker.
To prevent this, I use a strict whitelist strategy for caching status codes:
# Only cache successes (200) and permanent redirects (301)
proxy_cache_valid 200 301 5m;
# Cache "Not Found" briefly to prevent 404-scanning DoS attacks
proxy_cache_valid 404 1m;
Notice what is missing?
- 403 (Forbidden): Not listed, so never cached.
- 444 (No Response): Not listed, never cached.
- 500 (Server Error): Not listed, never cached.
By explicitly defining only the codes I want to keep, I ensure that WAF blocks and transient server errors are never stored. ModSecurity can block threats aggressively without risking the experience for valid visitors.
Verification
To prove it works I use curl to inspect the headers.
1. Public Page (Should HIT) Run this twice. The first request warms the cache and the second should hit it.
Bash
curl -I https://www.fracturedarchitecture.com/
Output:
HTTP
HTTP/2 200
x-cache-status: HIT
2. Admin Panel (Should MISS/BYPASS) We must verify that we haven't accidentally cached the login page.
Bash
curl -I https://www.fracturedarchitecture.com/ghost/
Output:
HTTP
HTTP/2 200
cache-control: no-cache, private
x-cache-status: BYPASS
The Freshness Trade-off (and the Python Solution)
You will notice in the configuration that I set the cache validity to 5 minutes:
proxy_cache_valid 200 301 5m;
This creates a deliberate 5-minute "consistency window." When I publish a new post or fix a typo, the change does not propagate to the public immediately. It takes up to 5 minutes for the old cache entry to expire and refresh.
Why not longer? If I set this to 1 hour, I would need to implement complex "cache purging" logic to clear the cache whenever I publish. The standard NGINX Ingress Controller does not support this easily without Lua scripting or third-party plugins.
Why not shorter? If I set it to 1 minute, the backend gets hit too often during traffic spikes.
Five minutes is the sweet spot. It provides massive protection for the infrastructure while keeping the content reasonably fresh. And because of the bypass logic I defined earlier, I (as the logged-in admin) see my changes instantly. The delay only applies to anonymous readers.
The Newsletter Problem
This 5-minute window creates one critical edge case: The Newsletter Blast.
If Ghost sends 1,000 emails the second I hit publish, my subscribers will click the link and hit the cached version of the homepage (which doesn't have the new post yet) or get a 404.
To solve this without complex cache purging logic, I wrote a custom Python batch script that handles my email delivery.
- Ghost publishes the post.
- My Python script detects the new content.
- The script sleeps for exactly 5 minutes.
- The script sends the emails.
By the time the first subscriber clicks the link in their inbox, the NGINX cache has naturally expired. The first request triggers a refresh from the backend, and everyone sees the new content.
It also gives me a 5-minute grace period to fix any glaring typos I missed before the email goes out to everyone. I let time do the work for me.
Expected Performance Impact
The difference is immediate and massive. We are moving from a heavy, single-threaded Node.js process to a lightweight, event-driven Nginx static file server.
Without Cache: Every request hits the Ghost backend. Node.js wakes up, queries the database, processes Handlebars templates, and assembles the HTML string. This takes 200ms - 600ms per request and burns significant CPU. Under load, requests queue up, and response times degrade linearly.
With Cache: Nginx serves the pre-made file instantly. It bypasses the database and the application logic entirely.
- Response Time: Drops to 2ms - 10ms.
- Concurrency: Nginx can handle thousands of concurrent connections without breaking a sweat.
- Scalability: The site can now withstand massive traffic spikes (like being featured on Hacker News) without crashing the database or requiring more pods.
Even though we configured a "Disk" cache (/tmp), Linux is smart. The operating system uses free RAM as a Page Cache, meaning frequently accessed files (like the homepage) are served directly from memory. You get the speed of RAM without the risk of running out of memory.
Conclusion
With this configuration, my Ghost blog is now lightning fast and production-ready. I have successfully decoupled my content delivery from my application logic, ensuring that my readers get instant page loads while my admin panel remains secure. Now I'll sleep well when this site goes viral.
Field Log Discussion
Public @handle only · Private email hidden · Fenced code blocks supported
Join the architecture review under a self-chosen @handle. Your email address is never displayed publicly.
Loading discussion notes...