Skip to content
LF Cert Trainer

Lesson 122 · Section 9: Networking

Lesson 122: A practical guide to Gateway API: from an empty cluster to routed, rewritten and split traffic

A hands-on walk through the Gateway API: check what is installed, create a Gateway, attach HTTPRoutes by host and path, add HTTPS with a redirect, rewrite a path prefix, split traffic by weight, convert an Ingress, and read the status conditions when something does not work. · 22 min read · 2 min video

1/8A practical guide to Gateway API
0:00 / 2:24

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

What this lesson does

Lesson 121 explained the Gateway API objects. This lesson is the workshop: every section is a task you can type into a cluster, in the order you would meet them. The scenario is the same throughout.

  • Namespace shop holds three Services: web on port 80, and cart-v1 and cart-v2 on port 8080.
  • The platform namespace infra will hold the Gateway.
  • The site is shop.example.com.
The order in which the pieces must exist1. CRDsthe API types2. Controllerrunning Pods3. GatewayClassAccepted4. GatewayProgrammed5. HTTPRouteAccepted6. Testcurl with Host
The order in which the pieces must exist. Each step depends on the one before it. In the exam the first three are normally done for you: check them, then start at step four or five.

Parts:

  • 1. CRDs (the API types)
  • 2. Controller (running Pods)
  • 3. GatewayClass (Accepted)
  • 4. Gateway (Programmed)
  • 5. HTTPRoute (Accepted)
  • 6. Test (curl with Host)

Connections:

  • 1. CRDs to 2. Controller
  • 2. Controller to 3. GatewayClass
  • 3. GatewayClass to 4. Gateway
  • 4. Gateway to 5. HTTPRoute
  • 5. HTTPRoute to 6. Test
What this lesson buildsGateway web (infra)come back on 443//cart/cartClientshop.example.comListener httpport 80Listener httpsport 443, TLSRoute redirect301 to httpsRoute shop/ and /cartService webport 80Service cart-v1weight 90Service cart-v2weight 10
What this lesson builds. One Gateway with two listeners in namespace infra, and routes in namespace shop that send traffic to three Services.

Parts:

  • Client (shop.example.com)
  • Listener http (port 80), in Gateway web (infra)
  • Listener https (port 443, TLS), in Gateway web (infra)
  • Route redirect (301 to https)
  • Route shop (/ and /cart)
  • Service web (port 80)
  • Service cart-v1 (weight 90)
  • Service cart-v2 (weight 10)

Connections:

  • Client to Listener http
  • Client to Listener https
  • Listener http to Route redirect
  • Route redirect to Listener https: come back on 443
  • Listener https to Route shop
  • Route shop to Service web: /
  • Route shop to Service cart-v1: /cart
  • Route shop to Service cart-v2: /cart

Step 1: check what the cluster has

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

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

No resources found

Three facts: the types exist, the class to use is called nginx, and there is no Gateway yet. Write down the class name; everything else in this lesson works with any controller.

Under the hood · If the first command prints nothing: installing the API and a controller

The Gateway API is not part of a Kubernetes release. On your own cluster you install it in two steps.

The CRDs, from the project's release page. The standard channel holds the stable resources:

kubectl apply --server-side -f \
  https://github.com/kubernetes-sigs/gateway-api/releases/download/<version>/standard-install.yaml

Take the version your controller's documentation asks for. --server-side is used because the CRDs are too large for the annotation that a normal kubectl apply writes.

A controller, with its own manifest or Helm chart, for example NGINX Gateway Fabric, Envoy Gateway, Cilium, Istio or Traefik. The installation creates the controller's Deployment and, with most controllers, the GatewayClass. Afterwards kubectl get gatewayclass must show ACCEPTED True.

In the exam you are not expected to choose and install a controller from memory. Either it is there already, or the task gives you the manifest or chart to apply.

Step 2: create the Gateway

apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: web
  namespace: infra
spec:
  gatewayClassName: nginx
  listeners:
    - name: http
      port: 80
      protocol: HTTP
      allowedRoutes:
        namespaces:
          from: All
kubectl apply -f gateway.yaml
kubectl -n infra get gateway web
NAME   CLASS   ADDRESS        PROGRAMMED   AGE
web    nginx   10.106.31.80   True         25s

PROGRAMMED True and an address: the controller has built the data plane for this Gateway. Many controllers do that by creating a Deployment and a Service next to the Gateway:

kubectl -n infra get deploy,svc
NAME                        READY   UP-TO-DATE   AVAILABLE
deployment.apps/web-nginx   1/1     1            1

NAME                TYPE       CLUSTER-IP     EXTERNAL-IP   PORT(S)
service/web-nginx   NodePort   10.106.31.80   <none>        80:31437/TCP

The names and the Service type depend on the controller. What matters is how to reach it: here, port 31437 on any node, or the cluster IP on port 80 from inside the cluster. On a cloud cluster the Service is usually of type LoadBalancer and the Gateway's ADDRESS is the public address.

Step 3: route by host and path

apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: shop
  namespace: shop
spec:
  parentRefs:
    - name: web
      namespace: infra
  hostnames:
    - shop.example.com
  rules:
    - matches:
        - path:
            type: PathPrefix
            value: /cart
      backendRefs:
        - name: cart-v1
          port: 8080
    - backendRefs:                 # no matches: everything else
        - name: web
          port: 80
kubectl apply -f route.yaml
kubectl -n shop get httproute
kubectl -n shop describe httproute shop
NAME   HOSTNAMES              AGE
shop   ["shop.example.com"]   8s

Status:
  Parents:
    Conditions:
      Reason:   Accepted
      Status:   True
      Type:     Accepted
      Reason:   ResolvedRefs
      Status:   True
      Type:     ResolvedRefs
    Controller Name:  gateway.nginx.org/nginx-gateway-controller
    Parent Ref:
      Name:       web
      Namespace:  infra

Both conditions are True. Now test, with the Host header, exactly as with an Ingress:

curl -s -H "Host: shop.example.com" http://node01:31437/            # answered by web
curl -s -H "Host: shop.example.com" http://node01:31437/cart        # answered by cart-v1
curl -s -o /dev/null -w '%{http_code}\n' http://node01:31437/       # 404: no route for this host

/cart is more specific than the catch-all rule, so it wins regardless of the order in which the rules are written.

Step 4: add HTTPS and redirect HTTP to it

Create the certificate Secret in the Gateway's namespace and add a second listener:

kubectl -n infra create secret tls shop-tls --cert=shop.crt --key=shop.key
  listeners:
    - name: http
      port: 80
      protocol: HTTP
      allowedRoutes:
        namespaces:
          from: All
    - name: https
      port: 443
      protocol: HTTPS
      hostname: shop.example.com
      tls:
        mode: Terminate
        certificateRefs:
          - name: shop-tls
      allowedRoutes:
        namespaces:
          from: All

Now two routes. The first attaches only to the http listener and does nothing but redirect:

apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: shop-redirect
  namespace: shop
spec:
  parentRefs:
    - name: web
      namespace: infra
      sectionName: http            # only the listener named http
  hostnames:
    - shop.example.com
  rules:
    - filters:
        - type: RequestRedirect
          requestRedirect:
            scheme: https
            statusCode: 301

A redirect rule has no backendRefs: the gateway answers by itself. The second route is the one from step 3, now pinned to the https listener by adding sectionName: https to its parentRefs.

curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' -H "Host: shop.example.com" http://node01:31437/cart
301 https://shop.example.com/cart

Step 5: rewrite a path prefix

The cart application serves its pages at /, not at /cart. In lesson 119 this needed an annotation, a regular expression and capture groups. Here it is a filter:

    - matches:
        - path:
            type: PathPrefix
            value: /cart
      filters:
        - type: URLRewrite
          urlRewrite:
            path:
              type: ReplacePrefixMatch
              replacePrefixMatch: /
      backendRefs:
        - name: cart-v1
          port: 8080
URLRewrite with ReplacePrefixMatchforwardsRequest/cart/items/7Match PathPrefix/cartReplacePrefixMatchreplace with /Pod receives/items/7
URLRewrite with ReplacePrefixMatch. The matched prefix is swapped for the replacement and the rest of the path is kept. No regular expression is involved.

Parts:

  • Request (/cart/items/7)
  • Match PathPrefix (/cart)
  • ReplacePrefixMatch (replace with /)
  • Pod receives (/items/7)

Connections:

  • Request to Match PathPrefix
  • Match PathPrefix to ReplacePrefixMatch
  • ReplacePrefixMatch to Pod receives: forwards
Client asks forPod receives
/cart/
/cart//
/cart/items/7/items/7
/cartoonnot matched by this rule

urlRewrite.path has two types:

typeFieldEffect
ReplacePrefixMatchreplacePrefixMatchReplaces the matched prefix, keeps the rest. Needs a PathPrefix match in the same rule
ReplaceFullPathreplaceFullPathReplaces the whole path with a fixed one

urlRewrite.hostname rewrites the Host header in the same way. A rule may have a URLRewrite or a RequestRedirect filter, not both.

Step 6: split traffic between two versions

      backendRefs:
        - name: cart-v1
          port: 8080
          weight: 90
        - name: cart-v2
          port: 8080
          weight: 10

Weights are proportions, not percentages: 90 and 10 behave like 9 and 1. A backend without weight has weight 1, and weight 0 sends it nothing, which is a tidy way to keep a version listed while it gets no traffic.

for i in $(seq 1 20); do curl -s -H "Host: shop.example.com" http://node01:31437/cart; done | sort | uniq -c
     18 cart v1
      2 cart v2

To move the release forward, change the weights to 50 and 50, then 0 and 100. To send only testers to the new version instead, add a second rule with a header match in front of the weighted one:

    - matches:
        - path: { type: PathPrefix, value: /cart }
          headers:
            - name: x-canary
              value: "true"
      backendRefs:
        - name: cart-v2
          port: 8080

A rule that also matches a header is more specific than one that only matches the path, so requests carrying x-canary: true take it.

Step 7: convert an Ingress

A typical exam-style task: "an Ingress site exists; create the equivalent Gateway API configuration".

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: site
  namespace: shop
spec:
  ingressClassName: nginx
  tls:
    - hosts: [shop.example.com]
      secretName: shop-tls
  rules:
    - host: shop.example.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: web
                port:
                  number: 80

Move each part to its new home:

From the IngressGoes to
ingressClassName: nginxGateway gatewayClassName (use a class from kubectl get gatewayclass; the names need not be equal)
tls.hosts, tls.secretNameGateway listener: protocol: HTTPS, hostname, tls.certificateRefs
rules[].hostHTTPRoute hostnames
path, pathType: Prefixmatches[].path with type: PathPrefix
backend.service.name, port.numberbackendRefs[].name, port
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: site
  namespace: shop
spec:
  gatewayClassName: nginx
  listeners:
    - name: https
      port: 443
      protocol: HTTPS
      hostname: shop.example.com
      tls:
        certificateRefs:
          - name: shop-tls
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: site
  namespace: shop
spec:
  parentRefs:
    - name: site
  hostnames:
    - shop.example.com
  rules:
    - matches:
        - path:
            type: PathPrefix
            value: /
      backendRefs:
        - name: web
          port: 80

Everything is in one namespace here, so allowedRoutes can stay at its default (Same), the Secret needs no ReferenceGrant, and parentRefs needs no namespace. Verify both objects, test, and only then delete the Ingress if the task asks for it.

When it does not work

Troubleshooting: read the status in this orderGatewayClassAccepted?GatewayProgrammed?HTTPRouteAccepted?HTTPRouteResolvedRefs?Servicehas endpoints?Request workscurl answers
Troubleshooting: read the status in this order. Each object reports whether its own part worked. The first False is the problem, and its reason names the cause.

Parts:

  • GatewayClass (Accepted?)
  • Gateway (Programmed?)
  • HTTPRoute (Accepted?)
  • HTTPRoute (ResolvedRefs?)
  • Service (has endpoints?)
  • Request works (curl answers)

Connections:

  • GatewayClass to Gateway
  • Gateway to HTTPRoute
  • HTTPRoute to HTTPRoute
  • HTTPRoute to Service
  • Service to Request works
What you seeWhereCause and fix
no matches for kind "Gateway" on applykubectlCRDs not installed, or a wrong apiVersion
GatewayClass ACCEPTED is not Trueget gatewayclassNo controller for this class is running
Gateway PROGRAMMED is False or emptyget gatewayWrong gatewayClassName, a port the controller cannot open, or a missing TLS Secret (listener reason InvalidCertificateRef)
Route Accepted: False, NotAllowedByListenersdescribe httprouteThe listener's allowedRoutes does not cover the route's namespace
Route Accepted: False, NoMatchingListenerHostnamedescribe httprouteRoute hostnames and listener hostname do not overlap
Route Accepted: False, NoMatchingParentdescribe httproutesectionName or port in parentRefs names no listener
Route status has no parents at alldescribe httprouteparentRefs names a Gateway that does not exist: wrong name or missing namespace
Route ResolvedRefs: False, BackendNotFounddescribe httprouteService name wrong, or in another namespace
Route ResolvedRefs: False, RefNotPermitteddescribe httprouteCross-namespace backend without a ReferenceGrant
All conditions True, gateway answers 404curlMissing or wrong Host header, or no rule matches the path
All conditions True, gateway answers 500 or 503curlThe Service has no ready endpoints or the wrong port

Example · A route in the wrong namespace of mind

kubectl -n shop describe httproute shop | grep -A6 Conditions
    Conditions:
      Message:  Backend ref to Service payments/pay not permitted by any ReferenceGrant
      Reason:   RefNotPermitted
      Status:   False
      Type:     ResolvedRefs

The route in shop points at Service pay in namespace payments. The owner of payments has to allow that, with a ReferenceGrant created in payments:

apiVersion: gateway.networking.k8s.io/v1
kind: ReferenceGrant
metadata:
  name: allow-shop-routes
  namespace: payments              # the namespace of the target
spec:
  from:
    - group: gateway.networking.k8s.io
      kind: HTTPRoute
      namespace: shop              # who may refer in
  to:
    - group: ""                    # the core API group
      kind: Service

On clusters with an older Gateway API release, ReferenceGrant is v1beta1. kubectl api-resources shows which version your cluster serves.

Tricks

Common mistakes

  • Writing the route first and discovering afterwards that there is no Gateway, or that its class is not accepted.
  • The Secret in the application's namespace. certificateRefs looks in the Gateway's namespace unless a ReferenceGrant says otherwise.
  • backendRefs in a redirect rule, or a redirect route attached to the HTTPS listener as well.
  • ReplacePrefixMatch without a PathPrefix match in the same rule: the route is rejected.
  • Treating weights as percentages that must add up to 100. They are proportions.
  • Putting the Service port under port.number, as in an Ingress. In backendRefs it is just port: 8080.
  • Testing without the Host header when the route has hostnames.
  • Testing on port 80 of a node when the gateway's Service is a NodePort.
  • Deleting the old Ingress before the new route is verified.

Recap

  • Look first: kubectl api-resources --api-group=gateway.networking.k8s.io, get gatewayclass, get gateway -A.
  • Gateway: class, listeners with port and protocol, allowedRoutes, and for HTTPS a Secret in its own namespace.
  • HTTPRoute: parentRefs (with namespace and sectionName when needed), hostnames, then rules.
  • Redirect is a RequestRedirect filter with no backends; a prefix rewrite is URLRewrite with ReplacePrefixMatch; a traffic split is two backendRefs with weight.
  • PROGRAMMED, Accepted and ResolvedRefs tell you which object to fix, and the reason tells you how.

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

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

  • Send about one request in ten to a new version of an application by weighting the backends of an HTTPRoute.

    Build · Level 2 · standard · target 10 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

  • Use HTTPRoute filters to redirect a retired path to its new home, and to remove a prefix before requests reach a backend.

    Build · Level 3 · challenge · target 20 min

Discussion

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