Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Cloud Native 33 min read

Mastering Kong on Kubernetes: Architecture, CRD Map & Plugin Mechanics

This article systematically explains Kong Gateway's architecture in Kubernetes, mapping active vs deprecated CRDs, detailing plugin lifecycle phases, priority rules, binding methods, and providing an end-to-end Gateway API configuration template with production pitfalls.

Laying the Skeleton: How Kong Runs in Kubernetes

In traditional VM or Docker deployments, Kong Gateway often relied on PostgreSQL and manual Admin API calls to create routes. Once moved into Kubernetes, the mainstream approach is almost entirely DB-less (no database) mode .

Kong Gateway's data plane is built on OpenResty (Nginx + LuaJIT). Its core abstractions are only five entity types: Service (backend service definition) Route (matching rules) Upstream and Target (load-balancing pool and real backend nodes) Consumer and Consumer Group (caller identity and grouping) Plugin (traffic interception and enhancement logic)

In Kubernetes, the control plane watches cluster resources — Ingress, HTTPRoute, Service, EndpointSlice, and various Kong CRDs — translates them in real time into a declarative JSON configuration, and pushes it via an in-memory Admin API to the data plane (Kong Proxy Pods). The whole process requires no external database; the cluster's etcd is the single source of truth.

It helps to clarify the control-plane naming to avoid confusion in documentation:

KIC (Kong Ingress Controller) : The original "translator" component that watches K8s resources and pushes config to Kong Gateway.

KGO (Kong Gateway Operator) : An "infrastructure butler" that uses the Operator pattern to automatically provision, scale, and upgrade Kong control-plane and data-plane Pods.

Kong Operator (KO 2.0+) : To solve the problem of Helm-installing KIC with many environment variables and split lifecycle/routing config, Kong merged KIC and KGO into a unified Kong Operator, managing everything via native CRDs like ControlPlane and Gateway. For new clusters, start directly with the official Kong Operator or latest Gateway API; existing clusters running standalone KIC 3.x remain supported.

An often-overlooked data-plane mechanism: Kong sends requests directly to Pod IPs by default, not through kube-proxy 's ClusterIP .

Following the architecture diagram left-to-right: the highlighted Kong data plane does not forward traffic to the Service virtual IP. Instead, the control plane syncs each Pod IP from K8s EndpointSlice into Kong Upstream as independent Target entries.

Figure 1: Control plane translates K8s resources and EndpointSlice to DB-less data plane; traffic connects directly to backend Pod IPs.

There are clear engineering reasons. If traffic went through kube-proxy, Kong would only see a fixed ClusterIP, making it impossible to perform active health checks, circuit-breaking removal, consistent hashing, or canary ratio-based splitting on individual backend Pods. By connecting directly to Pod IPs, Kubernetes handles service discovery only, while full Layer-7 traffic governance is delegated to Kong.

One Map to Clear Kong's Custom Resources (CRDs)

Kubernetes native Ingress and Service have limited expressiveness — they only describe "which domain/path goes to which backend" and cannot carry gateway capabilities like "auth, rate-limiting, circuit-breaking, secret management." All Kong configuration.konghq.com CRDs are essentially puzzle pieces that fill Kubernetes' gateway expression gaps.

Grouping them by responsibility reduces mental overhead: Plugin class ( KongPlugin, KongClusterPlugin), Identity class ( KongConsumer, KongConsumerGroup), Upstream governance class ( KongUpstreamPolicy), Secrets & Extensions class ( KongVault, KongCustomEntity). Besides these, several legacy deprecated resources must be recognized and avoided.

The panorama table below breaks resources down by "resource version, scope, core responsibility, binding & replacement methods"; the three orange-annotated items at the bottom are explicitly retired.

Figure 2: Kong Kubernetes CRD classification map, showing active resources, scopes, and deprecated resources with migration paths.

Reading this table hinges on avoiding two high-frequency traps.

First, stop creating KongIngress , TCPIngress , and UDPIngress .

In early versions, KongIngress was a "catch-all" CRD that could tweak route timeouts, retries, path stripping ( strip_path), and upstream health checks and load-balancing algorithms. Since KIC 3.5, KongIngress is officially deprecated and slated for removal. The split is now clean:

Route and proxy parameters (timeouts, retries, prefix preservation): use konghq.com/* annotations on Ingress (e.g., konghq.com/connect-timeout, konghq.com/strip-path), or native HTTPRoute fields in Gateway API.

Upstream governance parameters (consistent hashing, active/passive health checks): all move to KongUpstreamPolicy, attached via konghq.com/upstream-policy annotation on the corresponding Service.

Layer-4 TCP/UDP proxy : TCPIngress and UDPIngress are also deprecated; new projects should use Gateway API's TCPRoute, TLSRoute, or UDPRoute.

Second, understand field hierarchy: v1 legacy resources have no spec ; v1beta1 / v1alpha1 new resources require spec .

This is the most common YAML error. For historical compatibility, KongPlugin, KongClusterPlugin, and KongConsumer (all configuration.konghq.com/v1) place core fields directly at the top level with no spec: wrapper. For example, KongPlugin writes plugin: and config: at top level; KongConsumer writes username: and credentials: at top level.

Later-introduced KongUpstreamPolicy ( v1beta1), KongConsumerGroup ( v1beta1), KongVault ( v1alpha1), and KongCustomEntity ( v1alpha1) follow modern Kubernetes API conventions, placing config inside spec:. Wrong hierarchy triggers CRD schema validation errors immediately.

Fully Digest Kong Plugins: Lifecycle, Mounting, Priority & Custom Extensions

If CRDs are the gateway's static skeleton, plugins are the actual execution engine. To use plugins well, you must simultaneously understand four things: at which request step they trigger, how to attach them to resources, how multiple plugins order and override, and how to inject sensitive config and custom code.

1. How Requests Flow Through 6 Phases

Based on OpenResty's event model, Kong slices a complete proxy process into 6 plugin hook phases. The top-down pipeline diagram highlights the access phase in blue — most auth, rate-limiting, and request rewriting happen here, and it's where 401 or 429 short-circuit interceptions mainly occur.

Figure 3: Kong plugin 6-phase lifecycle pipeline; access phase carries core governance logic and can short-circuit on validation failure.

Phase responsibilities are distinct:

certificate : Runs during TLS handshake; used for dynamic certificate issuance or client cert validation.

rewrite : Executes globally before matching a specific Route and Service; suitable for early request rewriting.

access : Runs after route matching, before forwarding to upstream Pods. Plugins like key-auth, jwt, rate-limiting, request-transformer run here. If any plugin intercepts, the request returns 401 or 429 directly to the client — never reaches backend Pods.

header_filter and body_filter : After backend Pod responds, the return path passes through these sequentially. header_filter modifies response headers; body_filter processes response body in streaming chunks. Avoid heavy recomputation in body_filter or it will directly degrade throughput.

log : Triggered asynchronously after the full response is sent to the client; used for logging, Prometheus push, or stats collection; does not block main-path latency.

2. How to Attach Plugins to Target Resources

After defining a KongPlugin or KongClusterPlugin, it remains in "standby" until explicitly bound to a mount point. In Kubernetes there are two main paths:

Path A (recommended, Gateway API): Use ExtensionRef filter in HTTPRoute .

This is Gateway API's native standard extension syntax — structured, schema-validated, not reliant on fragile string annotation concatenation:

rules:
  - filters:
      - type: ExtensionRef
        extensionRef:
          group: configuration.konghq.com
          kind: KongPlugin
          name: api-rate-limit

Path B (classic annotation): Use konghq.com/plugins annotation.

On traditional Ingress, Service, KongConsumer, or KongConsumerGroup (annotations also work on HTTPRoute), add a comma-separated plugin list, e.g., konghq.com/plugins: api-key-auth, api-rate-limit. To make a cluster-level plugin apply unconditionally to all traffic without per-resource annotations, add global: "true" label to the KongClusterPlugin 's metadata.labels.

Key distinction: Annotation on Ingress scopes the plugin to Kong's Route scope; annotation on Service scopes it to Kong's Service scope. A Service may map to multiple Ingress routes; annotating the Service means all routes pointing to it share that policy.

3. Same-Type Plugin Conflicts: "Precise Override" by Scope, Not Accumulation

Suppose you configure a global KongClusterPlugin for "100 req/min", an HTTPRoute for "300 req/min", and a VIP KongConsumer for "1000 req/min". When that VIP accesses that route, what's the limit?

Answer: 1000 req/min . In Kong, the same plugin type executes only one instance per request, following "more specific entity combination = higher priority" override — not stacking multiple limiters . The official full scope has 12 combinations; in daily Kubernetes use, the core precedence from highest to lowest is: Consumer + Route + Service (most specific — hits exact user, route, service) Consumer Group + Route +

Service
Consumer

+ Route / Consumer +

Service
Consumer Group

+ Route / Consumer Group +

Service
Route

+

Service
Consumer

level only (bound on KongConsumer; outranks standalone Route and Service) Consumer Group level only (bound on KongConsumerGroup; if user belongs to multiple groups, alphabetical group name order decides) Route level (bound on Ingress or HTTPRoute) Service level (bound on K8s Service) Global level ( KongClusterPlugin with global: "true" label)

This enables elegant tiered strategies: "global lenient default + specific API tightening + VIP customer/group relaxation".

4. Different Plugins: Static PRIORITY vs Dynamic Ordering & Authorization Boundaries

When a request carries both key-auth and request-transformer, which runs first?

Kong hard-codes a static priority integer PRIORITY in each plugin's handler.lua. At phase entry, larger number runs first . For example, key-auth default priority is 1250, rate-limiting is 910, request-transformer is 801. Default order: auth → rate-limit → rewrite.

But business often needs the reverse: caller puts API Key in a custom header; you want request-transformer to copy it to standard apikey header first, then key-auth validates. Default priority (801 after 1250) causes immediate 401 Unauthorized.

To break default order, note version and authorization boundaries:

Dynamic plugin ordering ( ordering field) : In KongPlugin, configure ordering.before.access or ordering.after.access to temporarily adjust sequence. This capability is limited to Kong Enterprise and Konnect, and only affects the access phase (response phases like header_filter still follow static priority).

Kong OSS (open-source) : Does not support dynamic ordering config. On community edition, the only standard way to change execution order is to copy or write a custom Lua plugin and set its PRIORITY in handler.lua higher than the target plugin (e.g., 1300).

5. Injecting Secrets & Loading Custom Plugins into the Cluster

Never hard-code third-party webhook secrets, OIDC client secrets, or cloud provider keys into KongPlugin 's config: and commit to Git. Two standard approaches:

Reference K8s Secret ( configFrom ) : In KongPlugin or KongClusterPlugin, use configFrom.secretKeyRef pointing to a same-namespace Secret (note config and configFrom are mutually exclusive).

Reference external secret store ( KongVault ) : On KIC 3.1+, use cluster-scoped KongVault to integrate with env vars, AWS Secrets Manager, or HashiCorp Vault, then write {vault://...} expressions in plugins for dynamic resolution.

For your own lightweight Lua plugins (containing handler.lua and schema.lua), you don't need to rebuild the heavy gateway container image each time. Package the plugin directory as a Kubernetes ConfigMap:

kubectl create configmap kong-plugin-custom-header 
  --from-file=custom-header/ 
  -n kong

Then in the Kong Helm Chart values.yaml, mount that ConfigMap into the data plane and append it to the KONG_PLUGINS env var (must retain bundled or built-in plugins will all disappear):

env:
  plugins: "bundled,custom-header"

plugins:
  configMaps:
    - name: kong-plugin-custom-header
      pluginName: custom-header

For production clusters requiring strong immutable delivery, or when using Go-written external plugins, build a custom image with the plugin compiled in.

Assembling Parts into a Whole: End-to-End Gateway API + CRD Combination Template

After dissecting each component, here's how they collaborate in one namespace. Below is a complete config template (verified against official docs; not executed in a live cluster — replace placeholders with your cluster's Gateway name, namespace, and backend Service).

First, a resource-binding diagram shows object "pointers". The centered HTTPRoute at bottom is the traffic entry hub: above via ExtensionRef mounts auth and rate-limit plugins; right via backendRefs points to business Service, which via annotation connects upward to KongUpstreamPolicy; left identity line from bottom-left KongConsumer references top-left Secret credentials for key-auth validation on request arrival.

Figure 4: HTTPRoute, KongPlugin, KongConsumer, Secret, and KongUpstreamPolicy reference and binding relationships.

The full YAML manifests below all live in the app-prod namespace (assuming Kong control plane uses default kong IngressClass, or has claimed the corresponding GatewayClass):

# 1. Credential Secret: must carry konghq.com/credential label indicating credential type
apiVersion: v1
kind: Secret
metadata:
  name: partner-a-apikey
  namespace: app-prod
  labels:
    konghq.com/credential: key-auth
stringData:
  key: "replace-with-strong-random-key"
---
# 2. Caller Consumer: note v1 version has no spec level
apiVersion: configuration.konghq.com/v1
kind: KongConsumer
metadata:
  name: partner-a
  namespace: app-prod
  annotations:
    kubernetes.io/ingress.class: kong
username: partner-a
credentials:
  - partner-a-apikey
---
# 3. Auth plugin: v1 version likewise has no spec level
apiVersion: configuration.konghq.com/v1
kind: KongPlugin
metadata:
  name: api-key-auth
  namespace: app-prod
plugin: key-auth
config:
  key_names:
    - apikey
  hide_credentials: true
---
# 4. Rate-limit plugin: per authenticated Consumer, 100 req/min
apiVersion: configuration.konghq.com/v1
kind: KongPlugin
metadata:
  name: api-rate-limit
  namespace: app-prod
plugin: rate-limiting
config:
  minute: 100
  policy: local
  limit_by: consumer
---
# 5. Upstream governance policy: v1beta1 version, fields under spec
apiVersion: configuration.konghq.com/v1beta1
kind: KongUpstreamPolicy
metadata:
  name: orders-upstream-policy
  namespace: app-prod
spec:
  algorithm: least-connections
  healthchecks:
    active:
      type: http
      httpPath: /healthz
      healthy:
        interval: 5
        successes: 2
      unhealthy:
        interval: 5
        httpFailures: 3
---
# 6. Business Service: links upstream policy via annotation
apiVersion: v1
kind: Service
metadata:
  name: orders-svc
  namespace: app-prod
  annotations:
    konghq.com/upstream-policy: orders-upstream-policy
spec:
  selector:
    app: orders
  ports:
    - port: 80
      targetPort: 8080
---
# 7. Gateway API HTTPRoute: mounts two plugins via ExtensionRef
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: orders-route
  namespace: app-prod
spec:
  parentRefs:
    - name: kong-gateway
      namespace: kong # requires Gateway listener to allow cross-namespace routes, or same namespace as Gateway
  hostnames:
    - api.example.com
  rules:
    - matches:
        - path:
            type: PathPrefix
            value: /v1/orders
      filters:
        - type: ExtensionRef
          extensionRef:
            group: configuration.konghq.com
            kind: KongPlugin
            name: api-key-auth
        - type: ExtensionRef
          extensionRef:
            group: configuration.konghq.com
            kind: KongPlugin
            name: api-rate-limit
      backendRefs:
        - name: orders-svc
          port: 80

Chained together, when an external request carries header apikey: replace-with-strong-random-key to https://api.example.com/v1/orders, it first passes priority

1250
key-auth

validation, identifies partner-a, then priority

910
rate-limiting

counts by partner-a and allows, finally Kong forwards traffic directly to healthy orders Pods using least-connections algorithm and /healthz health-check results.

5 High-Frequency Production Pitfalls & Adoption Path

Once Kong actually runs in the cluster, the most recurring troubleshooting items are rarely syntax errors but these 5 boundary conditions:

Missing kubernetes.io/ingress.class annotation causes silent failure : Independent resources like KongConsumer, KongClusterPlugin, or KongVault without the correct controller-matching kubernetes.io/ingress.class annotation (e.g., "kong") are skipped by the control plane — no YAML error, no routing fault, just sudden discovery at request time that identity or plugins aren't effective.

Misusing policy: local rate-limiting in DB-less multi-replica : Configuring policy: local for convenience stores counters in each Kong Pod's memory. With 4 data-plane replicas, a 100 req/min per-node limit becomes ~400 req/min actual throughput. For precise global rate-limiting in production, use policy: redis (with a standalone Redis) or Enterprise's built-in cluster-sync rate-limiting.

Forgetting to sync CRD upgrades when upgrading Helm Chart : Helm doesn't auto-upgrade existing cluster CRD schemas. After upgrading KIC or Kong Operator, if KongUpstreamPolicy or new fields report unknown field or sync failure, it's usually because the cluster's CRD YAML is still old — manually kubectl apply the matching version's CRD manifests.

Cross-namespace plugin/policy references blocked by isolation : KongPlugin and KongUpstreamPolicy are namespace-scoped; HTTPRoute 's ExtensionRef can only reference same-namespace objects. For multi-team shared plugin policies, switch to cluster-scoped KongClusterPlugin. For Gateway API cross-namespace backend Service references, configure target namespace's ReferenceGrant; for cross-namespace Kong CRD references like KongVault, use KongReferenceGrant to explicitly allow.

Stuffing v1 fields into spec: or copying old docs using KongIngress : Verify API version before creating resources. KongPlugin, KongClusterPlugin, KongConsumer fields go top-level; for timeouts, retries, health checks, use Ingress annotations / HTTPRoute native fields + KongUpstreamPolicy — don't reintroduce the soon-to-be-removed KongIngress.

If your team plans to formally adopt or reorganize Kong in Kubernetes, advance steadily in three steps:

First, decide control-plane shape: new clusters prefer Kong Operator + Gateway API ( Gateway + HTTPRoute); existing Ingress clusters align paths first without forced full rewrite.

Migrate legacy KongIngress into route annotations and KongUpstreamPolicy; move sensitive config to configFrom.secretKeyRef or KongVault.

In a test namespace, run the minimal closed loop of "one KongConsumer + auth KongPlugin + rate-limit KongPlugin + KongUpstreamPolicy "; verify EndpointSlice direct Pod connectivity and monitoring/logging work; then gradually roll out to business services.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

KubernetesPluginAPI GatewayKongCRDGateway APIDB-lessKong Operator

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion