This guide shows you how to use Istio and Flagger to automate canary deployments.
Prerequisites
Flagger requires a Kubernetes cluster v1.16 or newer and Istio v1.5 or newer.
Install Istio with telemetry support and Prometheus:
istioctlmanifestinstall--setprofile=default# Suggestion: Please change release-1.8 in below command, to your real istio version.kubectlapply-fhttps://raw.githubusercontent.com/istio/istio/release-1.18/samples/addons/prometheus.yaml
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:
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/v2kind:HorizontalPodAutoscalername:podinfoservice:# service port numberport:9898# container port number or name (optional)targetPort:9898# Istio gateways (optional)gateways: - istio-system/public-gateway# 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:
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:
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 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 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 Istio 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 app.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# Istio gateways (optional)gateways: - istio-system/public-gateway# 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:10# session affinity configsessionAffinity:# name of the cookie usedcookieName:flagger-cookie# max age of the cookie (in seconds)# optional; defaults to 86400maxAge:21600metrics: - 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/"
Save the above resource as podinfo-canary-session-affinity.yaml and then apply it:
You can load app.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 with Istio.
Traffic mirroring
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 shadowing mirror: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
Performing a Canary deployment on a TCP (non HTTP) service is nearly identical to an HTTP Canary. Besides updating your Gateway document to support the TCP routing, the only difference is you have to set the appProtocol field to TCP inside of the service section of your Canary document.
Example:
apiVersion:networking.istio.io/v1alpha3kind:Gatewaymetadata:name:public-gatewaynamespace:istio-systemspec:selector:istio:ingressgatewayservers: - port:number:7070name:tcp-serviceprotocol:TCP# <== set the protocol to tcp herehosts: - "*"
apiVersion:flagger.app/v1beta1kind:Canary# omitted for brevityspec:service:port:7070appProtocol:TCP# <== set the appProtocol heretargetPort:7070portName:"tcp-service-port"
If the appProtocol equals TCP then Flagger will treat this as a Canary deployment for a TCP service. When it creates the VirtualService document it will add a TCP section to route requests between the primary and canary services. See Istio documentation for more information on this spec.
The resulting VirtualService will include a tcp section similar to what is shown below:
Once the Canary analysis begins, Flagger will be able to adjust the weights inside of this tcp section to advance the Canary deployment until it either runs into an error (and is halted) or it successfully reaches the end of the analysis and is Promoted.
It is also important to note that if you set appProtocol to anything other than TCP, for example if you set it to HTTP, it will perform the Canary and treat it as an HTTP service. The same remains true if you do not set appProtocol at all. It will ONLY treat a Canary as a TCP service if appProtocal equals TCP.