Skip to content
System design on Kubernetes · Chapter 5 of 20 Day 3: Gateway API with Envoy Gateway

Day 3: Gateway API with Envoy Gateway

Goal: Install Envoy Gateway alongside the Gateway API CRDs from k3s, make kurz reachable from outside through a Gateway, measure the price of the extra hop, place the proxies deliberately, and try out load balancing and a canary release · Duration: approx. 90 min · Prerequisite: Day 2

Briefing

  • In the predecessor course, HAProxy on s1 sat in front of the instances. In the cluster, the Gateway API takes over: a set of Kubernetes resources that several implementations understand. This course uses Envoy Gateway.
HAProxy on the VM Gateway API
Installation and process GatewayClass: which controller builds the Gateways
frontend with bind :80 Gateway with a listener on port 80
backend with server lines HTTPRoute with backendRefs to Services
balance roundrobin, leastconn, source BackendTrafficPolicy with loadBalancer
two backend blocks with weight Weights in the backendRefs
  • The roles are separate: whoever runs the platform creates GatewayClass and Gateway. Whoever runs an application only attaches an HTTPRoute to it.
  • Every hop costs something. Today you measure how much the path through the Gateway costs, and why it costs more on s1 than elsewhere.

Drill 1: What k3s already ships

You noticed it on Day 0: k3s installs the Gateway API CRDs itself, through a bundled Helm chart. Check which version and which channel:

# on s1
# All CRDs of the Gateway API
kubectl get crd | grep gateway.networking
# Version, channel and who owns the CRD (annotations)
kubectl get crd gateways.gateway.networking.k8s.io -o jsonpath='{.metadata.annotations}{"\n"}'
# The Helm chart k3s used to install them
kubectl -n kube-system get helmchart

Expected (abridged):

backendtlspolicies.gateway.networking.k8s.io   Namespaced   v1(storage)           2026-11-24T15:51:13Z
gatewayclasses.gateway.networking.k8s.io       Cluster      v1(storage),v1beta1   2026-11-24T15:51:13Z
gateways.gateway.networking.k8s.io             Namespaced   v1(storage),v1beta1   2026-11-24T15:51:13Z
grpcroutes.gateway.networking.k8s.io           Namespaced   v1(storage)           2026-11-24T15:51:13Z
httproutes.gateway.networking.k8s.io           Namespaced   v1(storage),v1beta1   2026-11-24T15:51:13Z
{"api-approved.kubernetes.io":"https://github.com/kubernetes-sigs/gateway-api/pull/4530","gateway.networking.k8s.io/bundle-version":"v1.6.3","gateway.networking.k8s.io/channel":"standard","helm.sh/resource-policy":"keep","meta.helm.sh/release-name":"gateway-api-crd","meta.helm.sh/release-namespace":"kube-system"}
NAME              REPO   CHART                                                                  VERSION   TARGETNAMESPACE   BOOTSTRAP   FAILED
gateway-api-crd          https://%{KUBERNETES_API}%/static/charts/gateway-api-crd-1.6.301.tgz                                           False

Gateway API 1.6.3, channel standard, managed by the Helm release gateway-api-crd in kube-system. The Gateway API comes in two channels: standard contains only stable fields, experimental also those that may still change. Remember both; they matter in a moment.

Save your progress? Sign up for free

Drill 2: Installing Envoy Gateway

The obvious way is the one from the Envoy Gateway docs, a helm install:

# on s1
# Install Envoy Gateway 1.10.0 with all bundled CRDs (as the docs say)
helm install eg oci://docker.io/envoyproxy/gateway-helm --version v1.10.0 \
  -n envoy-gateway-system --create-namespace

Expected (abridged):

Pulled: docker.io/envoyproxy/gateway-helm:v1.10.0
Error: INSTALLATION FAILED: failed to install CRD crds/gatewayapi-crds.yaml: server-side apply failed for object /gatewayclasses.gateway.networking.k8s.io apiextensions.k8s.io/v1, Kind=CustomResourceDefinition: customresourcedefinitions.apiextensions.k8s.io "gatewayclasses.gateway.networking.k8s.io" is forbidden: ValidatingAdmissionPolicy 'safe-upgrades.gateway.networking.k8s.io' with binding 'safe-upgrades.gateway.networking.k8s.io' denied request: Installing experimental CRDs on top of standard channel CRDs is prohibited by default. ...

The chart ships the Gateway API in the experimental channel. Together with the CRDs, k3s installed a guard rule, a ValidatingAdmissionPolicy named safe-upgrades, that forbids exactly this: putting experimental CRDs on top of standard CRDs. Nothing was changed; the CRDs are still at 1.6.3.

You have two options: remove the guard rule and the k3s CRDs and leave the Gateway API to Envoy Gateway, or leave the Gateway API with k3s and take only Envoy Gateway’s own CRDs. The second way keeps ownership clear: k3s updates the Gateway API with every update, Envoy Gateway only itself.

Envoy Gateway also ships its CRDs as a separate chart. There, the Gateway API CRDs and the Envoy CRDs can be switched on individually:

# on s1
# Working directory for today
mkdir -p ~/sdk/tag03 && cd ~/sdk/tag03
# Which switches does the CRD chart have?
helm show values oci://docker.io/envoyproxy/gateway-crds-helm --version v1.10.0 2>/dev/null

Expected:

crds:
  gatewayAPI:
    enabled: false
    channel: experimental   # Available options: standard, experimental
  envoyGateway:
    enabled: false
# on s1
# Render only Envoy's own CRDs as YAML (Gateway API stays off)
helm template eg-crds oci://docker.io/envoyproxy/gateway-crds-helm --version v1.10.0 \
  --set crds.envoyGateway.enabled=true > eg-crds.yaml 2>/dev/null
# How many CRDs are there?
grep -c "^kind: CustomResourceDefinition" eg-crds.yaml
# CRDs are big; server-side apply avoids the size limit of the apply annotation
kubectl apply --server-side -f eg-crds.yaml

Expected:

8
customresourcedefinition.apiextensions.k8s.io/backends.gateway.envoyproxy.io serverside-applied
customresourcedefinition.apiextensions.k8s.io/backendtrafficpolicies.gateway.envoyproxy.io serverside-applied
customresourcedefinition.apiextensions.k8s.io/clienttrafficpolicies.gateway.envoyproxy.io serverside-applied
customresourcedefinition.apiextensions.k8s.io/envoyextensionpolicies.gateway.envoyproxy.io serverside-applied
customresourcedefinition.apiextensions.k8s.io/envoypatchpolicies.gateway.envoyproxy.io serverside-applied
customresourcedefinition.apiextensions.k8s.io/envoyproxies.gateway.envoyproxy.io serverside-applied
customresourcedefinition.apiextensions.k8s.io/httproutefilters.gateway.envoyproxy.io serverside-applied
customresourcedefinition.apiextensions.k8s.io/securitypolicies.gateway.envoyproxy.io serverside-applied

Now Envoy Gateway itself, without CRDs:

# on s1
# Install the controller; crds.enabled=false turns off the CRD subchart, --skip-crds the crds folder
helm install eg oci://docker.io/envoyproxy/gateway-helm --version v1.10.0 \
  -n envoy-gateway-system --create-namespace --skip-crds --set crds.enabled=false
# Wait until the controller is running
kubectl -n envoy-gateway-system rollout status deploy/envoy-gateway
# Does the controller complain about missing CRDs?
kubectl -n envoy-gateway-system logs deploy/envoy-gateway | grep -i "crd not found"

Expected (abridged):

STATUS: deployed
deployment "envoy-gateway" successfully rolled out
2026-11-25T07:42:14.978Z    info    provider    kubernetes/controller.go:2766   ServiceImport CRD not found, skipping ServiceImport watch   {"runner": "provider"}

Only ServiceImport is missing, a resource for multi-cluster services. This course does not need it.

Caution: Envoy Gateway 1.10.0 ships Gateway API 1.6.1, k3s has 1.6.3. That fits here, because both are 1.6. If either side moves to a new minor version, check Envoy Gateway’s compatibility matrix before you update k3s or the chart.

Save your progress? Sign up for free

Drill 3: A Gateway for kurz

Three resources: the GatewayClass says which controller is responsible. The Gateway opens port 80. The HTTPRoute sends everything to the Service kurz.

# on s1
# Write GatewayClass, Gateway and HTTPRoute into one file
cat > gateway.yaml <<EOF
apiVersion: gateway.networking.k8s.io/v1
kind: GatewayClass
metadata:
  name: eg
spec:
  controllerName: gateway.envoyproxy.io/gatewayclass-controller
---
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: web
  namespace: kurz
spec:
  gatewayClassName: eg
  listeners:
  - name: http
    protocol: HTTP
    port: 80
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: kurz
  namespace: kurz
spec:
  parentRefs:
  - name: web
  rules:
  - backendRefs:
    - name: kurz
      port: 80
EOF
# Apply
kubectl apply -f gateway.yaml
# Wait until Envoy Gateway has built the Gateway
kubectl wait --for=condition=Programmed gateway/web -n kurz --timeout=180s
# Address of the Gateway
kubectl -n kurz get gateway web
# What appeared in the Envoy Gateway namespace?
kubectl -n envoy-gateway-system get pods,svc -o wide
# Who listens on port 80 on the nodes?
kubectl -n kube-system get pods -o wide | grep svclb
# Did the route find its Gateway and its Service?
kubectl -n kurz get httproute kurz -o jsonpath='{range .status.parents[0].conditions[*]}{.type}={.status} {end}{"\n"}'

Expected (abridged):

gatewayclass.gateway.networking.k8s.io/eg created
gateway.gateway.networking.k8s.io/web created
httproute.gateway.networking.k8s.io/kurz created
gateway.gateway.networking.k8s.io/web condition met
NAME   CLASS   ADDRESS        PROGRAMMED   AGE
web    eg      172.16.0.126   True         33s
pod/envoy-gateway-867b7df877-zjj5x             1/1     Running   0          56s   10.42.2.29   s2
pod/envoy-kurz-web-01987d52-5f8c87dbc5-rs79d   2/2     Running   0          32s   10.42.0.40   s1
service/envoy-kurz-web-01987d52   LoadBalancer   10.43.54.124    172.16.0.126   80:30639/TCP
svclb-envoy-kurz-web-01987d52-70826ba2-c5tgn   1/1     Running     0          33s   10.42.4.19   s3
svclb-envoy-kurz-web-01987d52-70826ba2-jcdkd   1/1     Running     0          33s   10.42.2.30   s2
svclb-envoy-kurz-web-01987d52-70826ba2-t8cdz   1/1     Running     0          33s   10.42.0.39   s1
Accepted=True ResolvedRefs=True

For each Gateway, Envoy Gateway creates its own Deployment with Envoy (envoy-kurz-web-…) and in front of it a Service of type LoadBalancer. In k3s, the built-in ServiceLB serves it: an svclb Pod on every node that forwards the node’s port 80 to the Service. As the address it reports only s1, but the Gateway is reachable on all three nodes:

# on s1
# Take a real code from the Day 2 list
cp ../tag02/mix.js ../tag02/codes.txt . && C=$(head -1 codes.txt)
# Request a redirect via every node IP on port 80
for ip in 172.16.0.126 172.16.0.228 172.16.0.83; do
  curl -s -o /dev/null -m 3 -w "$ip %{http_code} %{redirect_url}\n" http://$ip/$C
done

Expected:

172.16.0.126 302 https://example.org/tag12/anonym/393-11-1795477443020
172.16.0.228 302 https://example.org/tag12/anonym/393-11-1795477443020
172.16.0.83 302 https://example.org/tag12/anonym/393-11-1795477443020

Your target URL is a different one; what matters is the 302 on all three addresses. With that, kurz is reachable from outside the cluster for the first time in this course.

Save your progress? Sign up for free

Drill 4: What does the hop cost?

The same load directly on the Service and through the Gateway:

# on s1
# Direct path: the ClusterIP of the Service, as on Day 2
DIREKT=http://$(kubectl -n kurz get svc kurz -o jsonpath='{.spec.clusterIP}')
# Three levels, each once direct and once through the Gateway on s1
for r in 1000 2000 3000; do
  for z in direkt gateway; do
    [ $z = direkt ] && u=$DIREKT || u=http://172.16.0.126
    echo "== $r/s $z"
    ZIEL=$u RATE=$r DAUER=20s k6 run --quiet mix.js 2>/dev/null \
      | grep -E 'http_req_duration\.|http_req_failed\.|http_reqs\.' | sed 's/  */ /g'
  done
done

Expected:

== 1000/s direkt
 http_req_duration..............: avg=3.59ms min=788.45µs med=2.58ms max=42.47ms p(90)=6.61ms p(95)=9.26ms
 http_req_failed................: 0.00% 0 out of 20001
 http_reqs......................: 20001 999.887788/s
== 1000/s gateway
 http_req_duration..............: avg=12.69ms min=1.44ms med=7.9ms max=164.45ms p(90)=27.42ms p(95)=39.52ms
 http_req_failed................: 0.00% 0 out of 19939
 http_reqs......................: 19939 996.131699/s
== 2000/s direkt
 http_req_duration..............: avg=20.07ms min=566.06µs med=13.37ms max=201.57ms p(90)=46.56ms p(95)=60.81ms
 http_req_failed................: 0.00% 0 out of 38699
 http_reqs......................: 38699 1931.04991/s
== 2000/s gateway
 http_req_duration..............: avg=201.76ms min=1.74ms med=181.53ms max=1.22s p(90)=364.23ms p(95)=405.93ms
 http_req_failed................: 16.33% 5381 out of 32935
 http_reqs......................: 32935 1621.188563/s
== 3000/s direkt
 http_req_duration..............: avg=106.22ms min=715.38µs med=90.67ms max=739.28ms p(90)=209.59ms p(95)=265.21ms
 http_req_failed................: 2.16% 1069 out of 49413
 http_reqs......................: 49413 2448.902796/s
== 3000/s gateway
 http_req_duration..............: avg=252.43ms min=2.7ms med=247.64ms max=1.24s p(90)=395.19ms p(95)=434.38ms
 http_req_failed................: 28.08% 9408 out of 33501
 http_reqs......................: 33501 1653.7132/s
Rate Direct Through the Gateway
1000/s p95 9 ms, 0 errors p95 40 ms, 0 errors
2000/s 1931/s, 0 errors 1621/s, 16 % errors
3000/s 2449/s, 2 % errors 1654/s, 28 % errors

A single extra proxy, and throughput drops by a third. In the predecessor course it was similar with HAProxy: at 2000/s the path through HAProxy was slower than direct, because s1 carried everything at once. Check whether it is the same reason this time:

# on s1
# Resources of the Envoy Pod: what did Envoy Gateway set?
P=$(kubectl -n envoy-gateway-system get pods -l gateway.envoyproxy.io/owning-gateway-name=web -o name)
kubectl -n envoy-gateway-system get $P -o jsonpath='{range .spec.containers[*]}{.name} {.resources}{"\n"}{end}'
# 2000/s through the Gateway in the background, after 14 seconds the utilization of s1
(ZIEL=http://172.16.0.126 RATE=2000 DAUER=25s k6 run --quiet mix.js > k6-gw.txt 2>&1 &)
# Wait until the load is fully applied
sleep 14
# Overall utilization and the five biggest consumers
top -bn1 | sed -n 3p
top -bn1 -o %CPU | sed -n 8,12p | cut -c1-90

Expected:

envoy {"requests":{"cpu":"100m","memory":"512Mi"}}
shutdown-manager {"requests":{"cpu":"10m","memory":"32Mi"}}
%Cpu(s): 51.8 us, 32.1 sy,  0.0 ni,  1.8 id,  0.0 wa,  0.0 hi, 14.3 si,  0.0 st
 170485 ubuntu    20   0 1442760 185880  32396 S 175.0   1.5   0:18.24 k6
 169156 65532     20   0 3372872  96664  53336 S  68.8   0.8   1:16.48 envoy
 165940 65532     20   0 1272716  30904  10648 S  50.0   0.3   1:57.92 kurz
  73295 root      20   0 2391556 968336 187680 S  12.5   7.9 179:10.93 k3s-ser+
  73315 root      20   0 1570580 190460 138636 S  12.5   1.6  20:24.64 contain+

1.8 % idle. On s1, k6, Envoy, a kurz Pod, the database and the k3s server all run at the same time. The scheduler scores nodes by free capacity according to requests (Day 2), and s1, with four cores, has the most. So more lands there than elsewhere, Envoy included. The Gateway is not slow. It just stands in the most crowded place.

Save your progress? Sign up for free

Drill 5: Placing the proxies

How Envoy Gateway builds its proxies is controlled by an EnvoyProxy resource. The GatewayClass points to it. You ask for two replicas, none in zone-a (s1), and never two on the same node:

# on s1
# EnvoyProxy: two replicas, not in zone-a, at most one per node
cat > envoyproxy.yaml <<EOF
apiVersion: gateway.envoyproxy.io/v1alpha1
kind: EnvoyProxy
metadata:
  name: zwei-zonen
  namespace: envoy-gateway-system
spec:
  provider:
    type: Kubernetes
    kubernetes:
      envoyDeployment:
        replicas: 2
        pod:
          affinity:
            nodeAffinity:
              requiredDuringSchedulingIgnoredDuringExecution:
                nodeSelectorTerms:
                - matchExpressions:
                  - key: topology.kubernetes.io/zone
                    operator: NotIn
                    values: [zone-a]
            podAntiAffinity:
              requiredDuringSchedulingIgnoredDuringExecution:
              - labelSelector:
                  matchLabels:
                    app.kubernetes.io/component: proxy
                topologyKey: kubernetes.io/hostname
EOF
# Create
kubectl apply -f envoyproxy.yaml
# Point the GatewayClass to these settings
kubectl patch gatewayclass eg --type merge -p \
  '{"spec":{"parametersRef":{"group":"gateway.envoyproxy.io","kind":"EnvoyProxy","name":"zwei-zonen","namespace":"envoy-gateway-system"}}}'
# Wait until the Envoy Deployment has rolled out again
D=$(kubectl -n envoy-gateway-system get deploy -l gateway.envoyproxy.io/owning-gateway-name=web -o name)
kubectl -n envoy-gateway-system rollout status $D
# Where do the proxies run now?
kubectl -n envoy-gateway-system get pods -l app.kubernetes.io/component=proxy -o wide | awk '{print $1, $2, $7}'

Expected (abridged):

envoyproxy.gateway.envoyproxy.io/zwei-zonen created
gatewayclass.gateway.networking.k8s.io/eg patched
deployment "envoy-kurz-web-01987d52" successfully rolled out
NAME READY NODE
envoy-kurz-web-01987d52-b867444d5-cmmmm 2/2 s3
envoy-kurz-web-01987d52-b867444d5-p524f 2/2 s2

parametersRef is not in gateway.yaml. A later kubectl apply -f gateway.yaml still leaves the field in place, because it does not come from the last apply (Day 2, exercise). Here that is intended. Measure again, only through the Gateway:

# on s1
# The same three levels, only through the Gateway
for r in 1000 2000 3000; do
  echo "== $r/s gateway"
  ZIEL=http://172.16.0.126 RATE=$r DAUER=20s k6 run --quiet mix.js 2>/dev/null \
    | grep -E 'http_req_duration\.|http_req_failed\.|http_reqs\.' | sed 's/  */ /g'
done

Expected:

== 1000/s gateway
 http_req_duration..............: avg=11.28ms min=1.97ms med=7.48ms max=136.12ms p(90)=22.29ms p(95)=31.91ms
 http_req_failed................: 0.00% 0 out of 19933
 http_reqs......................: 19933 996.165047/s
== 2000/s gateway
 http_req_duration..............: avg=77.37ms min=2.42ms med=62.23ms max=456.57ms p(90)=161.68ms p(95)=198.53ms
 http_req_failed................: 0.00% 0 out of 37038
 http_reqs......................: 37038 1837.315951/s
== 3000/s gateway
 http_req_duration..............: avg=192.91ms min=3.2ms med=155.55ms max=1.23s p(90)=375.94ms p(95)=432.57ms
 http_req_failed................: 22.09% 8989 out of 40684
 http_reqs......................: 40684 2011.702274/s
Rate Gateway, Envoy on s1 Gateway, Envoy on s2 + s3
2000/s 1621/s, 16 % errors 1837/s, 0 errors
3000/s 1654/s, 28 % errors 2012/s, 22 % errors

At 2000/s, the errors disappear. The path through the Gateway stays more expensive than direct (p95 32 instead of 9 ms at 1000/s): every request now goes from k6 through ServiceLB and kube-proxy to an Envoy on s2 or s3, from there to a kurz Pod and on to the database on s1. That is the price of an entrance from outside. At 3000/s, s1 is full again, with k6, the database and a kurz Pod.

Save your progress? Sign up for free

Drill 6: How does Envoy balance?

kurz writes the header X-Kurz-Instanz with the Pod name into every response. With it you count who gets picked how often:

# on s1
# Function zaehle: 200 requests to /readyz, count instances
zaehle() {
  for i in $(seq 200); do
    curl -s -o /dev/null -D - http://172.16.0.126/readyz | grep -i x-kurz-instanz
  done | sort | uniq -c
}
# No setting: Envoy Gateway's default
zaehle

Expected:

     97 x-kurz-instanz: kurz-68d75bfb98-b2t95
    103 x-kurz-instanz: kurz-68d75bfb98-qxl5s

Envoy Gateway’s default is least request: of two randomly chosen targets, the one with fewer open requests gets the next one. With single curl calls one after another, that is close to 50/50. You switch the algorithm with a BackendTrafficPolicy. Like balance source in the predecessor course, each source IP should always hit the same instance:

# on s1
# Load balancing for the route kurz: consistent hash over the source IP
cat > lb.yaml <<EOF
apiVersion: gateway.envoyproxy.io/v1alpha1
kind: BackendTrafficPolicy
metadata:
  name: kurz-lb
  namespace: kurz
spec:
  targetRefs:
  - group: gateway.networking.k8s.io
    kind: HTTPRoute
    name: kurz
  loadBalancer:
    type: ConsistentHash
    consistentHash:
      type: SourceIP
EOF
# Apply and give Envoy a moment
kubectl apply -f lb.yaml && sleep 5
# Count again
zaehle
# Which source address does Envoy see? The last lines of its access log
kubectl -n envoy-gateway-system logs -l app.kubernetes.io/component=proxy -c envoy --tail=3 \
  | grep -o '"x-forwarded-for":"[^"]*"' | sort | uniq -c

Expected:

backendtrafficpolicy.gateway.envoyproxy.io/kurz-lb created
    100 x-kurz-instanz: kurz-68d75bfb98-b2t95
    100 x-kurz-instanz: kurz-68d75bfb98-qxl5s
      6 "x-forwarded-for":"10.42.0.39"

Exactly half and half, although all requests come from s1. Envoy does not see s1 as the source, but 10.42.0.39: the svclb Pod on s1 from Drill 3. ServiceLB replaces the source address (SNAT). Each of the two Envoys hashes the same address and sends everything to “its” Pod; kube-proxy spreads the connections randomly across the two Envoys. Hence 100/100. Session affinity by IP does not work behind ServiceLB. A property that the request itself carries does work:

# on s1
# Hash the X-Nutzer header instead of the source IP
sed -i 's/type: SourceIP/type: Header\n      header:\n        name: X-Nutzer/' lb.yaml
# Apply and give Envoy a moment
kubectl apply -f lb.yaml && sleep 5
# 100 requests each for two users
for n in anna ben; do
  echo "== X-Nutzer: $n"
  for i in $(seq 100); do
    curl -s -o /dev/null -D - -H "X-Nutzer: $n" http://172.16.0.126/readyz | grep -i x-kurz-instanz
  done | sort | uniq -c
done

Expected:

backendtrafficpolicy.gateway.envoyproxy.io/kurz-lb configured
== X-Nutzer: anna
    100 x-kurz-instanz: kurz-68d75bfb98-qxl5s
== X-Nutzer: ben
    100 x-kurz-instanz: kurz-68d75bfb98-b2t95

Each user always lands on the same instance, across both Envoys: both compute the same hash ring from the same endpoints. Back to the default for the coming days:

# on s1
# Delete the policy: least request again
kubectl delete -f lb.yaml

Save your progress? Sign up for free

Drill 7: A canary release

A new version should first get only 10 % of requests, and anyone who wants to test it should be able to reach it on purpose. For that you need a second version next to the first. Here it is the same image under a different name; that is enough for the mechanism:

# on s1
# Canary: its own Deployment and its own Service, same ConfigMap and same Secret
cat > kanarie.yaml <<EOF
apiVersion: apps/v1
kind: Deployment
metadata:
  name: kurz-kanarie
  namespace: kurz
spec:
  replicas: 1
  selector:
    matchLabels:
      app: kurz-kanarie
  template:
    metadata:
      labels:
        app: kurz-kanarie
    spec:
      containers:
      - name: kurz
        image: 172.16.0.126:5000/kurz:1.0
        ports:
        - name: http
          containerPort: 8080
        envFrom:
        - configMapRef:
            name: kurz
        env:
        - name: KURZ_INSTANZ
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        - name: DB_PASSWORT
          valueFrom:
            secretKeyRef:
              name: db-kurz
              key: password
        - name: KURZ_DB
          value: postgres://kurz:\$(DB_PASSWORT)@db-rw:5432/kurz
        readinessProbe:
          httpGet:
            path: /readyz
            port: http
        resources:
          requests:
            cpu: 250m
            memory: 32Mi
          limits:
            memory: 64Mi
        securityContext:
          runAsNonRoot: true
          runAsUser: 65532
---
apiVersion: v1
kind: Service
metadata:
  name: kurz-kanarie
  namespace: kurz
spec:
  selector:
    app: kurz-kanarie
  ports:
  - name: http
    port: 80
    targetPort: http
EOF
# Create and wait
kubectl apply -f kanarie.yaml && kubectl -n kurz rollout status deploy/kurz-kanarie

\$(DB_PASSWORT) with a backslash: in a heredoc without quotes, the shell would otherwise execute $(…) itself. Now the route with two rules. Envoy checks the more specific one first:

# on s1
# Rule 1: header X-Kanarie: ja -> canary only. Rule 2: everyone else 90/10
cat > route-kanarie.yaml <<EOF
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: kurz
  namespace: kurz
spec:
  parentRefs:
  - name: web
  rules:
  - matches:
    - headers:
      - name: X-Kanarie
        value: ja
    backendRefs:
    - name: kurz-kanarie
      port: 80
  - backendRefs:
    - name: kurz
      port: 80
      weight: 90
    - name: kurz-kanarie
      port: 80
      weight: 10
EOF
# Replace the route and give Envoy a moment
kubectl apply -f route-kanarie.yaml && sleep 5
# Function version: only the Deployment name from X-Kurz-Instanz (without the two hash parts)
version() {
  curl -s -o /dev/null -D - "$@" http://172.16.0.126/readyz \
    | awk 'tolower($1)=="x-kurz-instanz:" {print $2}' | tr -d '\r' | sed -E 's/-[a-z0-9]+-[a-z0-9]+$//'
}
echo "== ohne Header, 500 Anfragen"
for i in $(seq 500); do version; done | sort | uniq -c
echo "== X-Kanarie: ja, 20 Anfragen"
for i in $(seq 20); do version -H "X-Kanarie: ja"; done | sort | uniq -c

Expected:

httproute.gateway.networking.k8s.io/kurz configured
== ohne Header, 500 Anfragen
    451 kurz
     49 kurz-kanarie
== X-Kanarie: ja, 20 Anfragen
     20 kurz-kanarie

451 to 49, almost exactly 90/10 (“ohne Header, 500 Anfragen” means “without header, 500 requests”). With the header, every request reaches the canary. And if the canary is broken? Simulate it: no ready Pod any more.

# on s1
# Canary down to zero Pods
kubectl -n kurz scale deploy/kurz-kanarie --replicas=0 && sleep 8
# 500 redirects, count only the HTTP status
for i in $(seq 500); do curl -s -o /dev/null -w "%{http_code}\n" http://172.16.0.126/$C; done | sort | uniq -c

Expected:

deployment.apps/kurz-kanarie scaled
    450 302
     50 503

Exactly 10 % 503. The weight still applies, even when nobody answers behind the target any more. Envoy does not redirect the 10 % to the healthy version. So a weighted canary is not a safety net by itself. Someone or something (Argo Rollouts, Flagger) has to watch the error rate and set the weight to zero.

Clean-up: canary gone, route simple again.

# on s1
# Restore the original route from gateway.yaml
kubectl apply -f gateway.yaml
# Delete the canary
kubectl delete -f kanarie.yaml

Save your progress? Sign up for free

Exercise: Speed drills

  1. Show all routes attached to the Gateway web, with their status. Target time: 1 min
  2. Send only /api/ to the canary and everything else to kurz. Which rule do you write into the HTTPRoute? Target time: 3 min
  3. Why does kubectl -n kurz get gateway web show only s1 as the address, although all nodes answer? Target time: 2 min

Solution

# on s1
# 1: routes with Gateway, status Accepted and ResolvedRefs
kubectl -n kurz get httproute -o custom-columns='NAME:.metadata.name,GATEWAY:.spec.parentRefs[0].name,ACCEPTED:.status.parents[0].conditions[0].status'

Expected:

NAME   GATEWAY   ACCEPTED
kurz   web       True

For 2: a rule with a path match before the general rule:

  rules:
  - matches:
    - path:
        type: PathPrefix
        value: /api/
    backendRefs:
    - name: kurz-kanarie
      port: 80
  - backendRefs:
    - name: kurz
      port: 80

For 3: ServiceLB enters only one address into the Service’s status.loadBalancer; the Gateway takes it from there. The svclb Pods still listen on every node. A real load balancer in front (Day 13) would need all three addresses.

Save your progress? Sign up for free

Challenge

Your team no longer wants a fixed node IP in front of the Gateway, but an address that survives a node failure, like VRRP with keepalived in the predecessor course. What options do you have in k3s without a cloud load balancer? Name two, each with one advantage and one disadvantage, and say which question you have to settle first.

Solution

  • MetalLB in L2 mode (or kube-vip): a virtual IP moves via ARP to a live node, like keepalived. Advantage: one address, fast switchover. Disadvantage: all traffic runs through the one node that currently holds the IP; ServiceLB has to be turned off for it.
  • DNS with multiple A records pointing to all three nodes: advantage: nothing to install, load is spread. Disadvantage: clients hold on to dead addresses until the TTL expires and do not always retry.
  • MetalLB with BGP spreads across all nodes via routing, but needs a BGP-capable router.

Settle first: where is the database? As long as db-1 lives only on s1 with local-path (Day 1), a failure-proof address helps little: if s1 fails, the entrance is there, but the data is not. Days 6 and 7 solve that.

Save your progress? Sign up for free

Checkpoint

# on s1
# Gateway programmed, address present
kubectl -n kurz get gateway web --no-headers | awk '{print $1, $2, $4}'
# Two Envoy Pods, none on s1
kubectl -n envoy-gateway-system get pods -l app.kubernetes.io/component=proxy -o wide --no-headers | awk '{print $7}' | sort
# Route points only to kurz
kubectl -n kurz get httproute kurz -o jsonpath='{.spec.rules[*].backendRefs[*].name}{"\n"}'
# Gateway API CRDs still from k3s (1.6.3)
kubectl get crd gateways.gateway.networking.k8s.io -o jsonpath='{.metadata.annotations.gateway\.networking\.k8s\.io/bundle-version}{"\n"}'
# Redirect through the Gateway
curl -s -o /dev/null -w "%{http_code}\n" http://172.16.0.228/$(head -1 ~/sdk/tag03/codes.txt)

Expected:

web eg True
s2
s3
kurz
v1.6.3
302

Interview note

  • Ingress or Gateway API? Ingress knows only host and path; everything else lives in vendor-specific annotations. The Gateway API has header matches, weights and role separation (GatewayClass for the platform, Route for the application) in the standard, and the same routes run with Envoy Gateway, Cilium, Istio or NGINX Gateway Fabric.
  • Sticky sessions: by client IP only if the IP is preserved along the whole path (externalTrafficPolicy: Local, PROXY protocol). A hash over a header or cookie is more robust, and most robust is an application without session state.
  • Canary by weight: it distributes, but it does not protect. Without automatic evaluation of the error rate (Argo Rollouts, Flagger), a broken canary keeps getting its share.

Enterprise note

  • The Gateway API CRDs are cluster-wide. If they belong to the distributor (k3s, RKE2, OpenShift, a cloud provider), you do not install them on the side with a controller chart. The safe-upgrades rule from Drill 2 exists for exactly that.
  • In production, Gateways run with at least two replicas spread across zones, with a PodDisruptionBudget (Day 13) and TLS at the listener (cert-manager). Envoy Gateway can start dedicated proxies per Gateway; one team per Gateway separates the failure domains.
  • Rate limits, timeouts and retries come later in this course: rate limits in the Gateway (Day 11), timeouts and retries in the service mesh (Day 12).

Contents

More