Optional Extension: Enable Caching in Nginx (Reverse Proxy Lab)
1. Goal
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.
2. Step 1 – Define a Cache Path
Edit the main Nginx config file:
sudo nano /etc/nginx/nginx.confInside 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 sizemax_size=100m– limit cache sizeinactive=60m– cached items not accessed for 60 minutes are removed
Save and exit.
3. Step 2 – Enable Cache in Your Server Block
Edit your site config:
sudo nano /etc/nginx/sites-available/loadbalance.localInside 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 earlierproxy_cache_valid 200 1m;– cache HTTP 200 OK responses for 1 minuteX-Proxy-Cache– custom header with cache status (MISS,HIT,BYPASS, …)
Test and reload:
sudo nginx -t
sudo systemctl reload nginx4. Step 3 – Test the Cache
4.1 Initial Request
Run:
curl -I http://loadbalance.local/Look for the header:
X-Proxy-Cache: MISSThe first request typically results in MISS (nothing cached yet).
4.2 Subsequent Requests
Run:
for i in {1..5}; do curl -I http://loadbalance.local/; doneYou should now see:
X-Proxy-Cache: HITThis indicates the response is being served from cache.
5. Step 4 – Verify Cache Duration
-
Wait at least 1 minute (based on
proxy_cache_valid 200 1m). -
Call again:
curl -I http://loadbalance.local/
You should see the status go back to MISS, then HIT again on later requests.
6. Step 5 – Observe Caching Effects
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-Cacheheader change? - When did you see updated backend responses?