This guide shows you how to use Linkerd and Flagger to automate canary deployments.
Prerequisites
Flagger requires a Kubernetes cluster v1.21 or newer and Linkerd 2.14 or newer.
Install Linkerd and Prometheus (part of Linkerd Viz):
# The CRDs need to be installed beforehandlinkerdinstall--crds|kubectlapply-f-linkerdinstall|kubectlapply-f-linkerdvizinstall|kubectlapply-f-# For linkerd versions 2.12 and later, the SMI extension needs to be install in# order to enable TrafficSplitscurl-sLhttps://linkerd.github.io/linkerd-smi/install|shlinkerdsmiinstall|kubectlapply-f-
If you prefer Helm, these are the commands to install Linkerd, Linkerd Viz, Linkerd-SMI and Flagger:
helmrepoaddlinkerdhttps://helm.linkerd.io/stablehelminstalllinkerd-crdslinkerd/linkerd-crds-nlinkerd--create-namespace# See https://linkerd.io/2/tasks/generate-certificates/ for how to generate the# certs referred belowhelminstalllinkerd-control-planelinkerd/linkerd-control-plane \-nlinkerd \--set-fileidentityTrustAnchorsPEM=ca.crt \--set-fileidentity.issuer.tls.crtPEM=issuer.crt \--set-fileidentity.issuer.tls.keyPEM=issuer.key \helm installlinkerd-vizlinkerd/linkerd-viz-nlinkerd-viz--create-namespacehelminstallflaggerflagger/flagger \--nflagger-system \--setmeshProvider=gatewayapi:v1beta1 \--setmetricsServer=http://prometheus.linkerd-viz:9090 \--setlinkerdAuthPolicy.create=true
Bootstrap
Flagger takes a Kubernetes deployment and optionally a horizontal pod autoscaler (HPA), then creates a series of objects (Kubernetes deployments, ClusterIP services and SMI traffic split). These objects expose the application inside the mesh and drive the canary analysis and promotion.
Create a test namespace and enable Linkerd proxy injection:
Create a metrics template and canary custom resources for the podinfo deployment:
---apiVersion:flagger.app/v1beta1kind:MetricTemplatemetadata:name:success-ratenamespace:testspec:provider:type:prometheusaddress:http://prometheus.linkerd-viz:9090query:| sum( rate( response_total{ namespace="{{ namespace }}", deployment=~"{{ target }}", classification!="failure", direction="{{ variables.direction }}" }[{{ interval }}] ) ) / sum( rate( response_total{ namespace="{{ namespace }}", deployment=~"{{ target }}", direction="{{ variables.direction }}" }[{{ interval }}] ) ) * 100---apiVersion:flagger.app/v1beta1kind:MetricTemplatemetadata:name:latencynamespace:testspec:provider:type:prometheusaddress:http://prometheus.linkerd-viz:9090query:| histogram_quantile( 0.99, sum( rate( response_latency_ms_bucket{ namespace="{{ namespace }}", deployment=~"{{ target }}", direction="{{ variables.direction }}" }[{{ interval }}] ) ) by (le) )---apiVersion:flagger.app/v1beta1kind:Canarymetadata:name:podinfonamespace:testspec:# deployment referencetargetRef:apiVersion:apps/v1kind:Deploymentname:podinfo# HPA reference (optional)autoscalerRef:apiVersion:autoscaling/v2kind:HorizontalPodAutoscalername:podinfo# the maximum time in seconds for the canary deployment# to make progress before it is rollback (default 600s)progressDeadlineSeconds:60service:# ClusterIP port numberport:9898# container port number or name (optional)targetPort:9898# Reference to the Service that the generated HTTPRoute would attach to.gatewayRefs: - name:podinfonamespace:testgroup:corekind:Serviceport:9898analysis:# schedule interval (default 60s)interval:30s# 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:5# Linkerd Prometheus checksmetrics: - name:success-ratetemplateRef:name:success-ratenamespace:test# minimum req success rate (non 5xx responses)# percentage (0-100)thresholdRange:min:99interval:1mtemplateVariables:direction:inbound - name:latencytemplateRef:name:latencynamespace:test# maximum req duration P99# millisecondsthresholdRange:max:500interval:30stemplateVariables:direction:inbound# testing (optional)webhooks: - name:acceptance-testtype:pre-rollouturl:http://flagger-loadtester.test/timeout:30smetadata:type:bashcmd:"curl -sd 'test' http://podinfo-canary.test:9898/token | grep token" - name:load-testtype:rollouturl:http://flagger-loadtester.test/metadata:cmd:"hey -z 2m -q 10 -c 2 http://podinfo-canary.test:9898/"
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 half a minute.
After a couple of seconds Flagger will create the canary objects:
After the bootstrap, the podinfo deployment will be scaled to zero and the traffic to podinfo.test will be routed to the primary pods. During the canary analysis, the podinfo-canary.test address can be used to target directly the canary pods.
Automated canary promotion
Flagger implements a control loop that gradually shifts traffic to the canary while measuring key performance indicators like HTTP requests success rate, requests average duration and pod health. Based on analysis of the KPIs a canary is promoted or aborted, and the analysis result is published to Slack.
Trigger a canary deployment by updating the container image:
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:
Starting canary analysis for podinfo.test
Pre-rollout check acceptance-test passed
Advance podinfo.test canary weight 5
Advance podinfo.test canary weight 10
Advance podinfo.test canary weight 15
Halt podinfo.test advancement success rate 69.17% < 99%
Halt podinfo.test advancement success rate 61.39% < 99%
Halt podinfo.test advancement success rate 55.06% < 99%
Halt podinfo.test advancement request duration 1.20s > 0.5s
Halt podinfo.test advancement request duration 1.45s > 0.5s
Rolling back podinfo.test failed checks threshold reached 5
Canary failed! Scaling down podinfo.test
Custom metrics
The canary analysis can be extended with Prometheus queries.
Let's a define a check for not found errors. Edit the canary analysis and add the following metric:
The above configuration validates the canary version by checking if the HTTP 404 req/sec percentage is below three percent of the total traffic. If the 404s rate reaches the 3% threshold, then the analysis is aborted and the canary is marked as failed.
Trigger a canary deployment by updating the container image:
When using an ingress controller, the Linkerd traffic split does not apply to incoming traffic since NGINX in running outside of the mesh. In order to run a canary analysis for a frontend app, Flagger creates a shadow ingress and sets the NGINX specific annotations.
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.
Edit podinfo canary analysis, set the provider to nginx, add the ingress reference, remove the max/step weight and add the match conditions and iterations:
The above configuration will run an analysis for ten minutes targeting users that have a canary cookie set to always or those that call the service using the X-Canary: always header.
Note that the load test now targets the external address and uses the canary cookie.
Trigger a canary deployment by updating the container image: