This guide shows you how to use Istio and Flagger to automate canary deployments.
Flagger requires a Kubernetes cluster v1.16 or newer and Istio v1.5 or newer.
Install Istio with telemetry support and Prometheus:
istioctl manifest install --set profile=default​kubectl apply -f https://raw.githubusercontent.com/istio/istio/release-1.8/samples/addons/prometheus.yaml
Install Flagger in the istio-system
namespace:
kubectl apply -k github.com/fluxcd/flagger//kustomize/istio
Create an ingress gateway to expose the demo app outside of the mesh:
apiVersion: networking.istio.io/v1alpha3kind: Gatewaymetadata:name: public-gatewaynamespace: istio-systemspec:selector:istio: ingressgatewayservers:- port:number: 80name: httpprotocol: HTTPhosts:- "*"
Flagger takes a Kubernetes deployment and optionally a horizontal pod autoscaler (HPA), then creates a series of objects (Kubernetes deployments, ClusterIP services, Istio destination rules and virtual services). These objects expose the application inside the mesh and drive the canary analysis and promotion.
Create a test namespace with Istio sidecar injection enabled:
kubectl create ns testkubectl label namespace test istio-injection=enabled
Create a deployment and a horizontal pod autoscaler:
kubectl apply -k https://github.com/fluxcd/flagger//kustomize/podinfo?ref=main
Deploy the load testing service to generate traffic during the canary analysis:
kubectl apply -k https://github.com/fluxcd/flagger//kustomize/tester?ref=main
Create a canary custom resource (replace 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/v2beta2kind: HorizontalPodAutoscalername: podinfoservice:# service port numberport: 9898# container port number or name (optional)targetPort: 9898# Istio gateways (optional)gateways:- public-gateway.istio-system.svc.cluster.local# Istio virtual service host names (optional)hosts:- app.example.com# Istio traffic policy (optional)trafficPolicy:tls:# use ISTIO_MUTUAL when mTLS is enabledmode: DISABLE# Istio retry policy (optional)retries:attempts: 3perTryTimeout: 1sretryOn: "gateway-error,connect-failure,refused-stream"analysis:# 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: request-success-rate# minimum req success rate (non 5xx responses)# percentage (0-100)thresholdRange:min: 99interval: 1m- name: request-duration# maximum req duration P99# millisecondsthresholdRange:max: 500interval: 30s# testing (optional)webhooks:- name: acceptance-testtype: pre-rollouturl: http://flagger-loadtester.test/timeout: 30smetadata:type: bashcmd: "curl -sd 'test' http://podinfo-canary:9898/token | grep token"- name: load-testurl: http://flagger-loadtester.test/timeout: 5smetadata:cmd: "hey -z 1m -q 10 -c 2 http://podinfo-canary.test:9898/"
Note that when using Istio 1.4 you have to replace the request-duration
with a metric template.
Save the above resource as podinfo-canary.yaml and then apply it:
kubectl apply -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:
# applieddeployment.apps/podinfohorizontalpodautoscaler.autoscaling/podinfocanary.flagger.app/podinfo​# generateddeployment.apps/podinfo-primaryhorizontalpodautoscaler.autoscaling/podinfo-primaryservice/podinfoservice/podinfo-canaryservice/podinfo-primarydestinationrule.networking.istio.io/podinfo-canarydestinationrule.networking.istio.io/podinfo-primaryvirtualservice.networking.istio.io/podinfo
Trigger a canary deployment by updating the container image:
kubectl -n test set image deployment/podinfo \podinfod=stefanprodan/podinfo:3.1.1
Flagger detects that the deployment revision changed and starts a new rollout:
kubectl -n test describe canary/podinfo​Status:Canary Weight: 0Failed Checks: 0Phase: SucceededEvents:Type Reason Age From Message---- ------ ---- ---- -------Normal Synced 3m flagger New revision detected podinfo.testNormal Synced 3m flagger Scaling up podinfo.testWarning Synced 3m flagger Waiting for podinfo.test rollout to finish: 0 of 1 updated replicas are availableNormal Synced 3m flagger Advance podinfo.test canary weight 5Normal Synced 3m flagger Advance podinfo.test canary weight 10Normal Synced 3m flagger Advance podinfo.test canary weight 15Normal Synced 2m flagger Advance podinfo.test canary weight 20Normal Synced 2m flagger Advance podinfo.test canary weight 25Normal Synced 1m flagger Advance podinfo.test canary weight 30Normal Synced 1m flagger Advance podinfo.test canary weight 35Normal Synced 55s flagger Advance podinfo.test canary weight 40Normal Synced 45s flagger Advance podinfo.test canary weight 45Normal Synced 35s flagger Advance podinfo.test canary weight 50Normal Synced 25s flagger Copying podinfo.test template spec to podinfo-primary.testWarning Synced 15s flagger Waiting for podinfo-primary.test rollout to finish: 1 of 2 updated replicas are availableNormal Synced 5s flagger Promotion completed! Scaling down podinfo.test
Note that if you apply new changes to the deployment during the canary analysis, Flagger will restart the analysis.
A canary deployment is triggered by changes in any of the following objects:
Deployment PodSpec (container image, command, ports, env, resources, etc)
ConfigMaps mounted as volumes or mapped to environment variables
Secrets mounted as volumes or mapped to environment variables
You can monitor all canaries with:
watch kubectl get canaries --all-namespaces​NAMESPACE NAME STATUS WEIGHT LASTTRANSITIONTIMEtest podinfo Progressing 15 2019-01-16T14:05:07Zprod frontend Succeeded 0 2019-01-15T16:15:07Zprod backend Failed 0 2019-01-14T17:05:07Z
During the canary analysis you can generate HTTP 500 errors and high latency to test if Flagger pauses the rollout.
Trigger another canary deployment:
kubectl -n test set image deployment/podinfo \podinfod=stefanprodan/podinfo:3.1.2
Exec into the load tester pod with:
kubectl -n test exec -it flagger-loadtester-xx-xx sh
Generate HTTP 500 errors:
watch curl http://podinfo-canary:9898/status/500
Generate latency:
watch curl http://podinfo-canary:9898/delay/1
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: 0Failed Checks: 10Phase: FailedEvents:Type Reason Age From Message---- ------ ---- ---- -------Normal Synced 3m flagger Starting canary deployment for podinfo.testNormal Synced 3m flagger Advance podinfo.test canary weight 5Normal Synced 3m flagger Advance podinfo.test canary weight 10Normal Synced 3m flagger Advance podinfo.test canary weight 15Normal Synced 3m flagger Halt podinfo.test advancement success rate 69.17% < 99%Normal Synced 2m flagger Halt podinfo.test advancement success rate 61.39% < 99%Normal Synced 2m flagger Halt podinfo.test advancement success rate 55.06% < 99%Normal Synced 2m flagger Halt podinfo.test advancement success rate 47.00% < 99%Normal Synced 2m flagger (combined from similar events): Halt podinfo.test advancement success rate 38.08% < 99%Warning Synced 1m flagger Rolling back podinfo.test failed checks threshold reached 10Warning Synced 1m flagger Canary failed! Scaling down podinfo.test
For applications that perform read operations, Flagger can be configured to drive canary releases with traffic mirroring. Istio 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/maxWeight
with iterations
and by setting analysis.mirror
to true
:
apiVersion: flagger.app/v1beta1kind: Canarymetadata:name: podinfonamespace: testspec:analysis:# schedule intervalinterval: 1m# max number of failed metric checks before rollbackthreshold: 5# total number of iterationsiterations: 10# enable traffic shadowingmirror: true# weight of the traffic mirrored to your canary (defaults to 100%)mirrorWeight: 100metrics:- name: request-success-ratethresholdRange:min: 99interval: 1m- name: request-durationthresholdRange:max: 500interval: 1mwebhooks:- name: acceptance-testtype: pre-rollouturl: http://flagger-loadtester.test/timeout: 30smetadata:type: bashcmd: "curl -sd 'test' http://podinfo-canary:9898/token | grep token"- name: load-testurl: http://flagger-loadtester.test/timeout: 5smetadata:cmd: "hey -z 1m -q 10 -c 2 http://podinfo.test:9898/"
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
check primary pods health
switch live traffic back to primary
scale to zero the canary
send notification with the canary analysis result
The above procedure can be extended with custom metrics checks, webhooks, manual promotion approval and Slack or MS Teams notifications.