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
Official competencies this lesson covers
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
shopholds three Services:webon port 80, andcart-v1andcart-v2on port 8080. - The platform namespace
infrawill hold the Gateway. - The site is
shop.example.com.
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
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
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 for | Pod receives |
|---|---|
/cart | / |
/cart/ | / |
/cart/items/7 | /items/7 |
/cartoon | not matched by this rule |
urlRewrite.path has two types:
type | Field | Effect |
|---|---|---|
ReplacePrefixMatch | replacePrefixMatch | Replaces the matched prefix, keeps the rest. Needs a PathPrefix match in the same rule |
ReplaceFullPath | replaceFullPath | Replaces 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 Ingress | Goes to |
|---|---|
ingressClassName: nginx | Gateway gatewayClassName (use a class from kubectl get gatewayclass; the names need not be equal) |
tls.hosts, tls.secretName | Gateway listener: protocol: HTTPS, hostname, tls.certificateRefs |
rules[].host | HTTPRoute hostnames |
path, pathType: Prefix | matches[].path with type: PathPrefix |
backend.service.name, port.number | backendRefs[].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
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 see | Where | Cause and fix |
|---|---|---|
no matches for kind "Gateway" on apply | kubectl | CRDs not installed, or a wrong apiVersion |
GatewayClass ACCEPTED is not True | get gatewayclass | No controller for this class is running |
Gateway PROGRAMMED is False or empty | get gateway | Wrong gatewayClassName, a port the controller cannot open, or a missing TLS Secret (listener reason InvalidCertificateRef) |
Route Accepted: False, NotAllowedByListeners | describe httproute | The listener's allowedRoutes does not cover the route's namespace |
Route Accepted: False, NoMatchingListenerHostname | describe httproute | Route hostnames and listener hostname do not overlap |
Route Accepted: False, NoMatchingParent | describe httproute | sectionName or port in parentRefs names no listener |
| Route status has no parents at all | describe httproute | parentRefs names a Gateway that does not exist: wrong name or missing namespace |
Route ResolvedRefs: False, BackendNotFound | describe httproute | Service name wrong, or in another namespace |
Route ResolvedRefs: False, RefNotPermitted | describe httproute | Cross-namespace backend without a ReferenceGrant |
All conditions True, gateway answers 404 | curl | Missing or wrong Host header, or no rule matches the path |
All conditions True, gateway answers 500 or 503 | curl | The 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.
certificateRefslooks in the Gateway's namespace unless a ReferenceGrant says otherwise. backendRefsin a redirect rule, or a redirect route attached to the HTTPS listener as well.ReplacePrefixMatchwithout aPathPrefixmatch 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. InbackendRefsit is justport: 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(withnamespaceandsectionNamewhen needed),hostnames, then rules. - Redirect is a
RequestRedirectfilter with no backends; a prefix rewrite isURLRewritewithReplacePrefixMatch; a traffic split is twobackendRefswithweight. PROGRAMMED,AcceptedandResolvedRefstell 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.