Enable Proxy Caching

TL;DR

Apply the proxy-cache plugin using the KongPlugin CRD.

Prerequisites

This page is part of the Get started with Kong Operator and Konnect CRDs series.

Complete the previous page, Create a Service and Route before completing this page.

Set up the proxy-cache plugin

Use the KongPlugin CRD to enable proxy caching on a KongService. The following example:

  • Caches 200 OK responses
  • Applies to GET and HEAD requests
  • Targets responses with text/plain content type
  • Stores cached data in memory
  • Sets the cache TTL to 300 seconds (5 minutes)
echo '
kind: KongPlugin
apiVersion: configuration.konghq.com/v1
metadata:
  name: proxy-cache-all-endpoints
  namespace: kong
plugin: proxy-cache
config:
  response_code:
  - 200
  request_method:
  - GET
  - HEAD
  content_type:
  - text/plain; charset=utf-8
  cache_ttl: 300
  strategy: memory
' | kubectl apply -f -

Apply the plugin to the KongService

Apply the plugin by annotating the KongService with its name:

kubectl annotate -n kong kongservice service konghq.com/plugins=proxy-cache-all-endpoints --overwrite

Validation

Send a request to the Route and inspect the X-Cache-Status header. The first request finds nothing in the cache, so it is sent to the upstream Service and its response is cached:

curl -i "http://$PROXY_IP/echo" \
     --no-progress-meter --fail-with-body 

You should see the following header:

X-Cache-Status: Miss

Send the same request again. This time the response is served from the cache:

curl -i "http://$PROXY_IP/echo" \
     --no-progress-meter --fail-with-body 

You should see the following header:

X-Cache-Status: Hit

Responses stay cached for 300 seconds, as set in the cache_ttl field of the plugin configuration.

Help us make these docs great!

Kong Developer docs are open source. If you find these useful and want to make them better, contribute today!