This guide shows you how to use Gateway API and Flagger to automate canary deployments and A/B testing.
Prerequisites
Flagger requires a Kubernetes cluster v1.19 or newer and any mesh/ingress that implements the v1beta1 or the v1 version of Gateway API. We'll be using Istio for the sake of this tutorial, but you can use any other implementation.
istioctlinstall--setprofile=minimal-y# Suggestion: Please change release-1.20 in below command, to your real istio version.kubectlapply-fhttps://raw.githubusercontent.com/istio/istio/release-1.20/samples/addons/prometheus.yaml
Note: The above installation sets the mesh provider to be gatewayapi:v1. If your Gateway API implementation uses the v1beta1 CRDs, then set the --meshProvider value to gatewayapi:v1beta1.
Create a namespace for the Gateway:
kubectlcreatensistio-ingress
Create a Gateway that configures load balancing, traffic ACL, etc:
Flagger takes a Kubernetes deployment and optionally a horizontal pod autoscaler (HPA), then creates a series of objects (Kubernetes deployments, ClusterIP services, HTTPRoutes for the Gateway). These objects expose the application inside the mesh and drive the canary analysis and promotion.
Create a test namespace:
kubectlcreatenstest
Create a deployment and a horizontal pod autoscaler:
Create metric templates targeting the Prometheus server in the flagger-system namespace. The PromQL queries below are meant for Envoy, but you can change it to your ingress/mesh provider accordingly.
Save the above resource as metric-templates.yaml and then apply it:
kubectlapply-fmetric-templates.yaml
Create a canary custom resource (replace "www.example.com" with your own domain):
apiVersion:flagger.app/v1beta1kind:Canarymetadata:name:podinfonamespace:testspec:# deployment referencetargetRef:apiVersion:apps/v1kind:Deploymentname:podinfo# the maximum time in seconds for the canary deployment# to make progress before it is rollback (default 600s)progressDeadlineSeconds:60# HPA reference (optional)autoscalerRef:apiVersion:autoscaling/v2kind:HorizontalPodAutoscalername:podinfoservice:# service port numberport:9898# container port number or name (optional)targetPort:9898# Gateway API HTTPRoute host nameshosts: - www.example.com# Reference to the Gateway that the generated HTTPRoute would attach to.gatewayRefs: - name:gatewaynamespace:istio-ingressanalysis:# schedule interval (default 60s)interval:1m# max number of failed metric checks before rollbackthreshold:5# max traffic percentage routed to canary# percentage (0-100)maxWeight:50# canary increment step# percentage (0-100)stepWeight:10metrics: - name:error-rate# max error rate (5xx responses)# percentage (0-100)templateRef:name:error-ratenamespace:flagger-systemthresholdRange:max:1interval:1m - name:latencytemplateRef:name:latencynamespace:flagger-system# secondsthresholdRange:max:0.5interval:30s# testing (optional)webhooks: - name:smoke-testtype:pre-rollouturl:http://flagger-loadtester.test/timeout:15smetadata:type:bashcmd:"curl -sd 'anon' http://podinfo-canary.test:9898/token | grep token" - name:load-testurl:http://flagger-loadtester.test/timeout:5smetadata:cmd:"hey -z 2m -q 10 -c 2 -host www.example.com http://gateway-istio.istio-ingress/"
Save the above resource as podinfo-canary.yaml and then apply it:
kubectlapply-f./podinfo-canary.yaml
When the canary analysis starts, Flagger will call the pre-rollout webhooks before routing traffic to the canary. The canary analysis will run for five minutes while validating the HTTP metrics and rollout hooks every minute.
After a couple of seconds Flagger will create the canary objects:
Configure your DNS server with a CNAME record (AWS) or A record (GKE/AKS/DOKS) and point a domain e.g. www.example.com to the LB address.
Now you can access the podinfo UI using your domain address.
Note that you should be using HTTPS when exposing production workloads on internet. You can obtain free TLS certs from Let's Encrypt, read this guide on how to configure cert-manager to secure Istio with TLS certificates.
If you're using a local cluster via kind/k3s you can port forward the Envoy LoadBalancer service:
When the number of failed checks reaches the canary analysis threshold, the traffic is routed back to the primary, the canary is scaled to zero and the rollout is marked as failed.
kubectl -n test describe canary/podinfo
Status:
Canary Weight: 0
Failed Checks: 10
Phase: Failed
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal Synced 3m flagger Starting canary deployment for podinfo.test
Normal Synced 3m flagger Advance podinfo.test canary weight 5
Normal Synced 3m flagger Advance podinfo.test canary weight 10
Normal Synced 3m flagger Advance podinfo.test canary weight 15
Normal Synced 3m flagger Halt podinfo.test advancement error rate 69.17% > 1%
Normal Synced 2m flagger Halt podinfo.test advancement error rate 61.39% > 1%
Normal Synced 2m flagger Halt podinfo.test advancement error rate 55.06% > 1%
Normal Synced 2m flagger Halt podinfo.test advancement error rate 47.00% > 1%
Normal Synced 2m flagger (combined from similar events): Halt podinfo.test advancement error rate 38.08% > 1%
Warning Synced 1m flagger Rolling back podinfo.test failed checks threshold reached 10
Warning Synced 1m flagger Canary failed! Scaling down podinfo.test
Session Affinity
While Flagger can perform weighted routing and A/B testing individually, with Gateway API it can combine the two leading to a Canary release with session affinity. For more information you can read the deployment strategies docs.
Create a canary custom resource (replace www.example.com with your own domain):
apiVersion:flagger.app/v1beta1kind:Canarymetadata:name:podinfonamespace:testspec:# deployment referencetargetRef:apiVersion:apps/v1kind:Deploymentname:podinfo# the maximum time in seconds for the canary deployment# to make progress before it is rollback (default 600s)progressDeadlineSeconds:60# HPA reference (optional)autoscalerRef:apiVersion:autoscaling/v2kind:HorizontalPodAutoscalername:podinfoservice:# service port numberport:9898# container port number or name (optional)targetPort:9898# Gateway API HTTPRoute host nameshosts: - www.example.com# Reference to the Gateway that the generated HTTPRoute would attach to.gatewayRefs: - name:gatewaynamespace:istio-ingressanalysis:# schedule interval (default 60s)interval:1m# max number of failed metric checks before rollbackthreshold:5# max traffic percentage routed to canary# percentage (0-100)maxWeight:50# canary increment step# percentage (0-100)stepWeight:10# session affinity configsessionAffinity:# name of the cookie usedcookieName:flagger-cookie# max age of the cookie (in seconds)# optional; defaults to 86400maxAge:21600metrics: - name:error-rate# max error rate (5xx responses)# percentage (0-100)templateRef:name:error-ratenamespace:flagger-systemthresholdRange:max:1interval:1m - name:latencytemplateRef:name:latencynamespace:flagger-system# secondsthresholdRange:max:0.5interval:30s# testing (optional)webhooks: - name:smoke-testtype:pre-rollouturl:http://flagger-loadtester.test/timeout:15smetadata:type:bashcmd:"curl -sd 'anon' http://podinfo-canary.test:9898/token | grep token" - name:load-testurl:http://flagger-loadtester.test/timeout:5smetadata:cmd:"hey -z 2m -q 10 -c 2 -host www.example.com http://gateway-istio.istio-ingress/"
Save the above resource as podinfo-canary-session-affinity.yaml and then apply it:
You can load www.example.com in your browser and refresh it until you see the requests being served by podinfo:6.0.1. All subsequent requests after that will be served by podinfo:6.0.1 and not podinfo:6.0.0 because of the session affinity configured by Flagger in the HTTPRoute object.
A/B Testing
Besides weighted routing, Flagger can be configured to route traffic to the canary based on HTTP match conditions. In an A/B testing scenario, you'll be using HTTP headers or cookies to target a certain segment of your users. This is particularly useful for frontend applications that require session affinity.
Create a canary custom resource (replace "www.example.com" with your own domain):
apiVersion:flagger.app/v1beta1kind:Canarymetadata:name:podinfonamespace:testspec:# deployment referencetargetRef:apiVersion:apps/v1kind:Deploymentname:podinfo# the maximum time in seconds for the canary deployment# to make progress before it is rollback (default 600s)progressDeadlineSeconds:60# HPA reference (optional)autoscalerRef:apiVersion:autoscaling/v2kind:HorizontalPodAutoscalername:podinfoservice:# service port numberport:9898# container port number or name (optional)targetPort:9898# Gateway API HTTPRoute host nameshosts: - www.example.com# Reference to the Gateway that the generated HTTPRoute would attach to.gatewayRefs: - name:gatewaynamespace:istio-ingressanalysis:# schedule interval (default 60s)interval:1m# max number of failed metric checks before rollbackthreshold:5# max traffic percentage routed to canary# percentage (0-100)maxWeight:50# canary increment step# percentage (0-100)stepWeight:10metrics: - name:error-rate# max error rate (5xx responses)# percentage (0-100)templateRef:name:error-ratenamespace:flagger-systemthresholdRange:max:1interval:1m - name:latencytemplateRef:name:latencynamespace:flagger-system# secondsthresholdRange:max:0.5interval:30s# testing (optional)webhooks: - name:smoke-testtype:pre-rollouturl:http://flagger-loadtester.test/timeout:15smetadata:type:bashcmd:"curl -sd 'anon' http://podinfo-canary.test:9898/token | grep token" - name:load-testurl:http://flagger-loadtester.test/timeout:5smetadata:cmd:"hey -z 2m -q 10 -c 2 -host www.example.com -H 'X-Canary: insider' http://gateway-istio.istio-ingress/"
The above configuration will run an analysis for ten minutes targeting those users that have an insider cookie.
Save the above resource as podinfo-ab-canary.yaml and then apply it:
kubectlapply-f./podinfo-ab-canary.yaml
Trigger a canary deployment by updating the container image:
Flagger detects that the deployment revision changed and starts a new rollout:
kubectl -n test describe canary/podinfo
Status:
Failed Checks: 0
Phase: Succeeded
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal Synced 3m flagger New revision detected podinfo.test
Normal Synced 3m flagger Scaling up podinfo.test
Warning Synced 3m flagger Waiting for podinfo.test rollout to finish: 0 of 1 updated replicas are available
Normal Synced 3m flagger Advance podinfo.test canary iteration 1/10
Normal Synced 3m flagger Advance podinfo.test canary iteration 2/10
Normal Synced 3m flagger Advance podinfo.test canary iteration 3/10
Normal Synced 2m flagger Advance podinfo.test canary iteration 4/10
Normal Synced 2m flagger Advance podinfo.test canary iteration 5/10
Normal Synced 1m flagger Advance podinfo.test canary iteration 6/10
Normal Synced 1m flagger Advance podinfo.test canary iteration 7/10
Normal Synced 55s flagger Advance podinfo.test canary iteration 8/10
Normal Synced 45s flagger Advance podinfo.test canary iteration 9/10
Normal Synced 35s flagger Advance podinfo.test canary iteration 10/10
Normal Synced 25s flagger Copying podinfo.test template spec to podinfo-primary.test
Warning Synced 15s flagger Waiting for podinfo-primary.test rollout to finish: 1 of 2 updated replicas are available
Normal Synced 5s flagger Promotion completed! Scaling down podinfo.test
Traffic mirroring
For applications that perform read operations, Flagger can be configured to do B/G tests with traffic mirroring. Gateway API traffic mirroring will copy each incoming request, sending one request to the primary and one to the canary service. The response from the primary is sent back to the user and the response from the canary is discarded. Metrics are collected on both requests so that the deployment will only proceed if the canary metrics are within the threshold values.
Note that mirroring should be used for requests that are idempotent or capable of being processed twice (once by the primary and once by the canary).
You can enable mirroring by replacing stepWeight with iterations and by setting analysis.mirror to true:
apiVersion:flagger.app/v1beta1kind:Canarymetadata:name:podinfonamespace:testspec:# deployment referencetargetRef:apiVersion:apps/v1kind:Deploymentname:podinfoservice:# service port numberport:9898# container port number or name (optional)targetPort:9898# Gateway API HTTPRoute host nameshosts: - www.example.com# Reference to the Gateway that the generated HTTPRoute would attach to.gatewayRefs: - name:gatewaynamespace:istio-ingressanalysis:# schedule intervalinterval:1m# max number of failed metric checks before rollbackthreshold:5# total number of iterationsiterations:10# enable traffic shadowingmirror:true# Gateway API HTTPRoute host namesmetrics: - name:request-success-ratethresholdRange:min:99interval:1m - name:request-durationthresholdRange:max:500interval:1mwebhooks: - name:load-testurl:http://flagger-loadtester.test/timeout:5smetadata:cmd:"hey -z 2m -q 10 -c 2 -host www.example.com http://gateway-istio.istio-ingress/"
With the above configuration, Flagger will run a canary release with the following steps:
detect new revision (deployment spec, secrets or configmaps changes)
scale from zero the canary deployment
wait for the HPA to set the canary minimum replicas
check canary pods health
run the acceptance tests
abort the canary release if tests fail
start the load tests
mirror 100% of the traffic from primary to canary
check request success rate and request duration every minute
abort the canary release if the metrics check failure threshold is reached
stop traffic mirroring after the number of iterations is reached
route live traffic to the canary pods
promote the canary (update the primary secrets, configmaps and deployment spec)
wait for the primary deployment rollout to finish
wait for the HPA to set the primary minimum replicas