Skip to content

Linux Exercise 11a - optional - Caching

Optional Extension: Enable Caching in Nginx (Reverse Proxy Lab)

Section titled “Optional Extension: Enable Caching in Nginx (Reverse Proxy Lab)”

In this extension you will:

  • Configure Nginx to cache responses from the backend pool
  • Verify that repeated requests are served from cache
  • Observe cache behavior when you change backend responses

You should add this on top of your existing loadbalance.local setup.


Edit the main Nginx config file:

Terminal window
sudo nano /etc/nginx/nginx.conf

Inside the http { ... } block, add:

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=mycache:10m
max_size=100m inactive=60m use_temp_path=off;

Explanation:

  • mycache:10m – name of cache zone + metadata size
  • max_size=100m – limit cache size
  • inactive=60m – cached items not accessed for 60 minutes are removed

Save and exit.


3. Step 2 – Enable Cache in Your Server Block

Section titled “3. Step 2 – Enable Cache in Your Server Block”

Edit your site config:

Terminal window
sudo nano /etc/nginx/sites-available/loadbalance.local

Inside the server { ... } block, modify your location /:

location / {
proxy_cache mycache;
proxy_cache_valid 200 1m;
add_header X-Proxy-Cache $upstream_cache_status;
proxy_pass http://backend_pool;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}

Explanation:

  • proxy_cache mycache; – use the cache zone configured earlier
  • proxy_cache_valid 200 1m; – cache HTTP 200 OK responses for 1 minute
  • X-Proxy-Cache – custom header with cache status (MISS, HIT, BYPASS, …)

Test and reload:

Terminal window
sudo nginx -t
sudo systemctl reload nginx

Run:

Terminal window
curl -I http://loadbalance.local/

Look for the header:

X-Proxy-Cache: MISS

The first request typically results in MISS (nothing cached yet).

Run:

Terminal window
for i in {1..5}; do curl -I http://loadbalance.local/; done

You should now see:

X-Proxy-Cache: HIT

This indicates the response is being served from cache.


  1. Wait at least 1 minute (based on proxy_cache_valid 200 1m).

  2. Call again:

    Terminal window
    curl -I http://loadbalance.local/

You should see the status go back to MISS, then HIT again on later requests.


Try changing one backend to respond differently (e.g. backend 1 returns {"backend":"1-changed"}) while the cache is active.

  • You may still see the old data until cache expires.
  • This shows that clients are no longer hitting backends directly for each request.

Describe your observations in your protocol:

  • How did the X-Proxy-Cache header change?
  • When did you see updated backend responses?