Skip to content
LF Cert Trainer

Lesson 121 · Section 9: Networking

Lesson 121: Gateway API: the successor to Ingress

Why Ingress ran out of room, how the Gateway API splits the work into GatewayClass, Gateway and HTTPRoute for three roles, how a route attaches to a gateway, what routes can do without annotations, and how to read the status that tells you whether it worked. · 20 min read · 3 min video

1/9Gateway API
0:00 / 2:45

Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.

Why it exists

Ingress did its job for years, and the last two lessons showed where it stops:

  • One object, two jobs. An Ingress holds the entry point's settings (class, TLS certificate) and the application's routes. The platform team and the application team edit the same object, and RBAC cannot separate "may add a path" from "may change the certificate".
  • Annotations for everything else. Rewrites, redirects, header changes, timeouts and traffic splitting are not in the API. They live in annotations that differ per controller and are never validated.
  • HTTP only. No TCP, UDP or gRPC routing.
  • No feedback. An Ingress has almost no status. A rule that the controller ignores looks the same as one that works.

The Ingress API is now frozen: it stays, and it gets nothing new. The Gateway API is the replacement the Kubernetes project recommends, and the CKA curriculum lists it by name.

What it is

Three objects for three rolesownsownsownsclassattachesbackendRefsInfrastructureproviderCluster operatorplatform teamApp developerone per teamGatewayClasswhich controllerGatewayports, TLS, whoHTTPRoutehost, path, backendServicethe application
Three objects for three roles. Each object is owned by a different person and protected by ordinary RBAC. The application developer can change routes without being able to touch ports, certificates or the load balancer.

Parts:

  • Infrastructure (provider)
  • Cluster operator (platform team)
  • App developer (one per team)
  • GatewayClass (which controller)
  • Gateway (ports, TLS, who)
  • HTTPRoute (host, path, backend)
  • Service (the application)

Connections:

  • Infrastructure to GatewayClass: owns
  • Cluster operator to Gateway: owns
  • App developer to HTTPRoute: owns
  • Gateway to GatewayClass: class
  • HTTPRoute to Gateway: attaches
  • HTTPRoute to Service: backendRefs
ObjectScopeOwnerSays
GatewayClassClusterInfrastructure provider"Gateways of this class are implemented by that controller"
GatewayNamespaceCluster operator"Listen on these ports, with these protocols and certificates, and accept routes from these namespaces"
HTTPRouteNamespaceApplication developer"Requests for this host and path go to that Service"
ReferenceGrantNamespaceOwner of the target"Objects from that namespace may refer to my Services or Secrets"

All of them are in the API group gateway.networking.k8s.io. GatewayClass, Gateway and HTTPRoute are v1.

Two facts set the Gateway API apart from everything else in this course:

  • It is not built into Kubernetes. The objects are CustomResourceDefinitions (lesson 90) that somebody installs into the cluster. On a cluster without them, kubectl get gateway answers the server doesn't have a resource type "gateway".
  • Like Ingress, it needs a controller. The CRDs are only the vocabulary. A Gateway controller, such as NGINX Gateway Fabric, Envoy Gateway, Istio, Cilium or Traefik, watches the objects and does the work. Many of them also create the proxy Deployment and its Service for you when you create a Gateway.

Coming from Ingress

The same job, split differentlybecomesbecomesandbecomeIngressClassIngress APIGatewayClassGateway APIIngressTLS and rulesGatewaylisteners, TLSHTTPRouterules, backendsAnnotationsrewrite, redirectFilterstyped fields
The same job, split differently. Ingress puts the entry point and the routing into one object and everything else into annotations. Gateway API gives each concern its own typed place.

Parts:

  • IngressClass (Ingress API)
  • GatewayClass (Gateway API)
  • Ingress (TLS and rules)
  • Gateway (listeners, TLS)
  • HTTPRoute (rules, backends)
  • Annotations (rewrite, redirect)
  • Filters (typed fields)

Connections:

  • IngressClass to GatewayClass: becomes
  • Ingress to Gateway: becomes
  • Gateway to HTTPRoute: and
  • Annotations to Filters: become
Ingress worldGateway API
IngressClassGatewayClass
Ingress controller's entry point, plus spec.tlsGateway with listeners
spec.rules (host, path, backend)HTTPRoute hostnames and rules
ingressClassNameGateway: gatewayClassName. Route: parentRefs
Annotations for rewrite, redirect, headersfilters in the route rule
pathType: Prefix / Exactpath.type: PathPrefix / Exact
Backend must be in the same namespaceOther namespaces allowed, with a ReferenceGrant
Almost no statusConditions on every object

How it works

GatewayClass

apiVersion: gateway.networking.k8s.io/v1
kind: GatewayClass
metadata:
  name: nginx
spec:
  controllerName: gateway.nginx.org/nginx-gateway-controller

It is installed together with the controller. You rarely write one; you look up its name:

kubectl get gatewayclass
NAME    CONTROLLER                                   ACCEPTED   AGE
nginx   gateway.nginx.org/nginx-gateway-controller   True       9d

ACCEPTED True means a running controller has claimed the class. Unknown or empty means no controller is there, and nothing built on this class will work.

Gateway

apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: web
  namespace: infra
spec:
  gatewayClassName: nginx
  listeners:
    - name: http                 # unique within the Gateway; routes can target it by this name
      port: 80
      protocol: HTTP
      allowedRoutes:
        namespaces:
          from: All              # Same (default), All or Selector
    - name: https
      port: 443
      protocol: HTTPS
      hostname: "*.example.com"  # optional: only requests for these names
      tls:
        mode: Terminate          # the default
        certificateRefs:
          - name: example-tls    # a kubernetes.io/tls Secret in the Gateway's namespace
Listener fieldMeaning
nameLabel of the listener. A route selects it with parentRefs[].sectionName
port, protocolWhere it listens: HTTP, HTTPS, TLS, TCP, UDP
hostnameOptional filter on the host name; wildcards such as *.example.com are allowed
tlsFor HTTPS: the certificate Secret. mode: Terminate decrypts at the gateway; Passthrough leaves it to the backend
allowedRoutes.namespaces.fromWho may attach: Same namespace (the default), All, or namespaces matching a Selector

HTTPRoute

apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: shop
  namespace: shop
spec:
  parentRefs:
    - name: web                  # the Gateway
      namespace: infra           # needed when the Gateway is in another namespace
      sectionName: http          # optional: only this listener
  hostnames:
    - shop.example.com
  rules:
    - matches:
        - path:
            type: PathPrefix
            value: /cart
      backendRefs:
        - name: cart             # a Service
          port: 8080
FieldMeaning
parentRefsThe Gateway (or Gateways) this route wants to attach to
hostnamesHost names this route answers for. Empty means "whatever the listener accepts"
rules[].matchesConditions on the request: path, headers, queryParams, method
rules[].filtersChanges to the request or response before it is forwarded
rules[].backendRefsServices (name and port) that receive the request, each with an optional weight

A rule without matches matches every path: the default is a prefix match on /.

Attachment: both sides must agree

Attachment is a two-sided agreementGateway web, namespace infraasksrefuseddecidesroutesHTTPRoute shopnamespace shopHTTPRoute testnamespace sandboxListener httpallowedRoutesSelectorexpose=trueService shopnamespace shop
Attachment is a two-sided agreement. The route asks for a gateway with parentRefs. The gateway's listener decides which namespaces may attach with allowedRoutes. A route from a namespace that is not allowed stays detached.

Parts:

  • HTTPRoute shop (namespace shop)
  • HTTPRoute test (namespace sandbox)
  • Listener http (allowedRoutes), in Gateway web, namespace infra
  • Selector (expose=true), in Gateway web, namespace infra
  • Service shop (namespace shop)

Connections:

  • HTTPRoute shop to Listener http: asks
  • HTTPRoute test to Listener http: refused
  • Selector to Listener http: decides
  • Listener http to Service shop: routes

A route is used only when two things are true:

  1. The route names the Gateway in parentRefs (and, optionally, one listener with sectionName).
  2. The listener allows the route: its allowedRoutes.namespaces covers the route's namespace, and the route's hostnames overlap with the listener's hostname if both are set.

The default of allowedRoutes.namespaces.from is Same. So a route in namespace shop does not attach to a Gateway in namespace infra until the Gateway's owner opens the listener, with All or with a selector:

      allowedRoutes:
        namespaces:
          from: Selector
          selector:
            matchLabels:
              expose: "true"       # namespaces that carry this label

This is the security model in one sentence: the application team chooses its routes, and the platform team chooses who is allowed to use the entry point.

Matching and precedence

Inside a matches list, each item is an alternative (OR). Inside one item, all conditions must hold (AND):

      matches:
        - path: { type: PathPrefix, value: /cart }
          headers:
            - name: x-beta          # /cart AND the header
              value: "true"
        - path: { type: Exact, value: /basket }    # OR exactly /basket
path.typeMatches
PathPrefix (default)By path segment, like Ingress Prefix: /cart matches /cart/7, not /cartoon
ExactOnly this path
RegularExpressionA pattern; support depends on the controller

When several rules match, the most specific wins: an exact path before a prefix, a longer prefix before a shorter one, then a rule with a method match, then the rule with more header matches. A request that matches no rule gets a 404 from the gateway.

Filters instead of annotations

What happens to one requestHTTPS9 of 101 of 10Clientshop.example.comGateway listenerport 443, TLSHTTPRoute rulematches: /cartFiltersrewrite, headersService cart-v1weight 90Service cart-v2weight 10
What happens to one request. The listener accepts the connection, the route's hostnames and matches select a rule, filters change the request, and the rule's backends receive it, split by weight when there are several.

Parts:

  • Client (shop.example.com)
  • Gateway listener (port 443, TLS)
  • HTTPRoute rule (matches: /cart)
  • Filters (rewrite, headers)
  • Service cart-v1 (weight 90)
  • Service cart-v2 (weight 10)

Connections:

  • Client to Gateway listener: HTTPS
  • Gateway listener to HTTPRoute rule
  • HTTPRoute rule to Filters
  • Filters to Service cart-v1: 9 of 10
  • Filters to Service cart-v2: 1 of 10
Filter typeWhat it doesReplaces the Ingress annotation
URLRewriteRewrites the path or the host name before forwardingrewrite-target
RequestRedirectAnswers with a redirect: other scheme, host, path or portssl-redirect, app-root
RequestHeaderModifierSets, adds or removes request headerscustom snippets
ResponseHeaderModifierThe same for response headerscustom snippets
RequestMirrorSends a copy of the request to a second backendmirror-target

And traffic splitting needs no filter at all: list two backendRefs with a weight each. The next lesson uses each of these in a real task.

Status: the API tells you whether it worked

Every object reports conditions, and they are the first place to look.

ObjectConditionTrue means
GatewayClassAcceptedA controller implements this class
GatewayAcceptedThe controller understood the Gateway
GatewayProgrammedThe proxy is configured and has an address
HTTPRoute, per parentAcceptedThe Gateway let the route attach
HTTPRoute, per parentResolvedRefsEvery backend it names exists and may be referenced
kubectl -n infra get gateway web
kubectl -n shop describe httproute shop
NAME   CLASS   ADDRESS        PROGRAMMED   AGE
web    nginx   203.0.113.20   True         4m

A Gateway also counts the routes on each listener (attachedRoutes in its status). When a condition is False, its reason says why: NotAllowedByListeners (the namespace is not allowed), NoMatchingListenerHostname (the host names do not overlap), BackendNotFound (no such Service), RefNotPermitted (a cross-namespace reference without a ReferenceGrant).

Under the hood · Cross-namespace references, other route kinds and release channels
  • ReferenceGrant. A route may send traffic to a Service in another namespace, and a Gateway may use a certificate Secret from another namespace, but only if the owner of the target agrees. The owner creates a ReferenceGrant in the target's namespace that names the kind and namespace allowed to refer in. Without it the reference is refused and ResolvedRefs is False with reason RefNotPermitted. Do not confuse the two directions: allowedRoutes lets routes attach to a Gateway; ReferenceGrant lets objects refer to a Service or Secret.
  • Other route kinds. GRPCRoute routes gRPC by service and method. TLSRoute, TCPRoute and UDPRoute cover traffic that is not HTTP. For the exam, HTTPRoute is the one to know.
  • Release channels. The project publishes two CRD bundles: standard, with the stable resources, and experimental, which adds newer ones. Which resources and API versions your cluster has depends on what was installed: kubectl api-resources --api-group=gateway.networking.k8s.io shows them.
  • Conformance levels. Features are marked Core (every controller must support them), Extended (optional but portable) or implementation-specific. Path, header and method matching, weights and header modifiers are Core; rewrites and mirroring are Extended, so check your controller before relying on them.
  • Not only for traffic from outside. The same route objects can describe traffic between Services inside a mesh. That use is outside the CKA.

Ingress or Gateway API?

SituationUse
An existing cluster full of Ingress objects that workKeep Ingress; it is stable and supported
A new cluster or a new applicationGateway API
You need rewrites, redirects, header rules or traffic splittingGateway API: typed fields instead of annotations
Several teams share one entry pointGateway API: separate objects and allowedRoutes
The task says "Ingress" or names an IngressClassIngress
The task says "Gateway", "HTTPRoute" or names a GatewayClassGateway API

Using it

Example · Find out what the cluster offers

kubectl api-resources --api-group=gateway.networking.k8s.io
kubectl get gatewayclass
kubectl get gateway -A
NAME               SHORTNAMES   APIVERSION                       NAMESPACED   KIND
gatewayclasses     gc           gateway.networking.k8s.io/v1     false        GatewayClass
gateways           gtw          gateway.networking.k8s.io/v1     true         Gateway
httproutes                      gateway.networking.k8s.io/v1     true         HTTPRoute
referencegrants    refgrant     gateway.networking.k8s.io/v1     true         ReferenceGrant

Three answers in three commands: the CRDs are installed, which class names exist, and whether a Gateway is already there for your route to attach to.

Example · Expose one Service through an existing Gateway

A Gateway web exists in namespace infra and accepts routes from all namespaces. Send shop.example.com to Service shop on port 80 in namespace shop.

apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: shop
  namespace: shop
spec:
  parentRefs:
    - name: web
      namespace: infra
  hostnames:
    - shop.example.com
  rules:
    - backendRefs:
        - name: shop
          port: 80

No matches, so every path of that host goes to the Service. Check that it attached:

kubectl -n shop get httproute shop -o jsonpath='{range .status.parents[0].conditions[*]}{.type}={.status} {.reason}{"\n"}{end}'
Accepted=True Accepted
ResolvedRefs=True ResolvedRefs

Example · A route that does not attach

Accepted=False NotAllowedByListeners
ResolvedRefs=True ResolvedRefs

The route is fine; the Gateway refuses it. Look at the listener:

kubectl -n infra get gateway web -o jsonpath='{.spec.listeners[*].allowedRoutes}'
{"namespaces":{"from":"Same"}}

Same: only routes in namespace infra may attach. Either the Gateway owner changes the listener to All or to a selector that matches your namespace, or the task expects the route in the Gateway's namespace.

Tricks

Common mistakes

  • Assuming the Gateway API is always there. It is a set of CRDs plus a controller. Check api-resources and get gatewayclass first.
  • Writing ingressClassName in a Gateway, or gatewayClassName in an HTTPRoute. The class goes on the Gateway; the route uses parentRefs.
  • Forgetting allowedRoutes. The default is Same, so routes in other namespaces are refused.
  • Leaving out namespace in parentRefs when the Gateway is in another namespace.
  • Using Ingress spellings. It is PathPrefix, not Prefix; backendRefs with name and port, not backend.service.port.number; hostnames, a list, not host.
  • Host names that do not overlap. A route for shop.example.com on a listener with hostname: "*.internal.test" never matches.
  • Pointing a route at a Service in another namespace without a ReferenceGrant.
  • Skipping the status. The conditions name the problem; guessing wastes time.

Recap

  • The Ingress API is frozen; the Gateway API is its successor. Both are in the CKA curriculum.
  • GatewayClass names the controller, Gateway opens listeners (port, protocol, TLS), HTTPRoute holds the routing.
  • A route attaches with parentRefs, and the listener must allow its namespace with allowedRoutes.
  • Rules have matches, filters and backendRefs; rewrites, redirects and weights are fields, not annotations.
  • The objects are CRDs and need a controller. Read Accepted, Programmed and ResolvedRefs to see what happened.

Official docs

Quiz: check what you learned

5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.

Sign in to take the quiz and keep your score.

Practise: try it on a real cluster

2 hands-on labs for this lesson. You get goals, not steps: any solution that reaches them passes.

  • Create a Gateway in the platform team's namespace and attach a route from the shop team's namespace to it.

    Build · Level 2 · standard · target 15 min

  • Section capstone. Repair a Service and a Pod's name resolution, then move the shop from an Ingress to a Gateway with routes that keep its paths, strip a prefix and redirect an old host name.

    Build · Level 3 · challenge · target 35 min

Discussion

Learners ask and answer questions here. Sign in to read and join the discussion.