Flagger
Search…
Gateway API Canary Deployments
This guide shows you how to use Gateway API and Flagger to automate canary deployments and A/B testing.
Flagger Canary Stages

Prerequisites

Flagger requires a Kubernetes cluster v1.16 or newer and any mesh/ingress that implements the v1alpha2 of Gateway API. We'll be using Contour for the sake of this tutorial, but you can use any other implementation.
Install the GatewayAPI CRDs:
1
kubectl apply -k github.com/kubernetes-sigs/gateway-api/config/crd?ref=v0.4.1
Copied!
Install a cluster-wide GatewayClass; a Gateway belonging to the GatewayClass and Contour components in the projectcontour namespace:
1
kubectl apply -f https://raw.githubusercontent.com/projectcontour/contour/release-1.20/examples/render/contour-gateway.yaml
Copied!
Install Flagger in the flagger-system namespace:
1
kubectl apply -k github.com/fluxcd/flagger//kustomize/gatewayapi
Copied!

Bootstrap

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:
1
kubectl create ns test
Copied!
Create a deployment and a horizontal pod autoscaler:
1
kubectl apply -k https://github.com/fluxcd/flagger//kustomize/podinfo?ref=main
Copied!
Deploy the load testing service to generate traffic during the canary analysis:
1
kubectl apply -k https://github.com/fluxcd/flagger//kustomize/tester?ref=main
Copied!
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.
1
apiVersion: flagger.app/v1beta1
2
kind: MetricTemplate
3
metadata:
4
name: latency
5
namespace: flagger-system
6
spec:
7
provider:
8
type: prometheus
9
address: http://flagger-prometheus:9090
10
query: |
11
histogram_quantile(0.99,
12
sum(
13
rate(
14
envoy_cluster_upstream_rq_time_bucket{
15
envoy_cluster_name=~"{{ namespace }}_{{ target }}-canary_[0-9a-zA-Z-]+",
16
}[{{ interval }}]
17
)
18
) by (le)
19
)/1000
20
---
21
apiVersion: flagger.app/v1beta1
22
kind: MetricTemplate
23
metadata:
24
name: error-rate
25
namespace: flagger-system
26
spec:
27
provider:
28
type: prometheus
29
address: http://flagger-prometheus:9090
30
query: |
31
100 - sum(
32
rate(
33
envoy_cluster_upstream_rq{
34
envoy_cluster_name=~"{{ namespace }}_{{ target }}-canary_[0-9a-zA-Z-]+",
35
envoy_response_code!~"5.*"
36
}[{{ interval }}]
37
)
38
)
39
/
40
sum(
41
rate(
42
envoy_cluster_upstream_rq{
43
envoy_cluster_name=~"{{ namespace }}_{{ target }}-canary_[0-9a-zA-Z-]+",
44
}[{{ interval }}]
45
)
46
)
47
* 100
Copied!
Save the above resource as metric-templates.yaml and then apply it:
1
kubectl apply -f metric-templates.yaml
Copied!
Create a canary custom resource (replace "loaclproject.contour.io" with your own domain):
1
apiVersion: flagger.app/v1beta1
2
kind: Canary
3
metadata:
4
name: podinfo
5
namespace: test
6
spec:
7
# deployment reference
8
targetRef:
9
apiVersion: apps/v1
10
kind: Deployment
11
name: podinfo
12
# the maximum time in seconds for the canary deployment
13
# to make progress before it is rollback (default 600s)
14
progressDeadlineSeconds: 60
15
# HPA reference (optional)
16
autoscalerRef:
17
apiVersion: autoscaling/v2beta2
18
kind: HorizontalPodAutoscaler
19
name: podinfo
20
service:
21
# service port number
22
port: 9898
23
# container port number or name (optional)
24
targetPort: 9898
25
# Gateway API HTTPRoute host names
26
hosts:
27
- localproject.contour.io
28
# Reference to the Gateway that the generated HTTPRoute would attach to.
29
gatewayRefs:
30
- name: contour
31
namespace: projectcontour
32
analysis:
33
# schedule interval (default 60s)
34
interval: 1m
35
# max number of failed metric checks before rollback
36
threshold: 5
37
# max traffic percentage routed to canary
38
# percentage (0-100)
39
maxWeight: 50
40
# canary increment step
41
# percentage (0-100)
42
stepWeight: 10
43
metrics:
44
- name: error-rate
45
# max error rate (5xx responses)
46
# percentage (0-100)
47
templateRef:
48
name: error-rate
49
namespace: flagger-system
50
thresholdRange:
51
max: 1
52
interval: 1m
53
- name: latency
54
templateRef:
55
name: latency
56
namespace: flagger-system
57
# seconds
58
thresholdRange:
59
max: 0.5
60
interval: 30s
61
# testing (optional)
62
webhooks:
63
- name: smoke-test
64
type: pre-rollout
65
url: http://flagger-loadtester.test/
66
timeout: 15s
67
metadata:
68
type: bash
69
cmd: "curl -sd 'anon' http://podinfo-canary.test:9898/token | grep token"
70
- name: load-test
71
url: http://flagger-loadtester.test/
72
timeout: 5s
73
metadata:
74
cmd: "hey -z 2m -q 10 -c 2 -host localproject.contour.io http://envoy.projectcontour/"
Copied!
Save the above resource as podinfo-canary.yaml and then apply it:
1
kubectl apply -f ./podinfo-canary.yaml
Copied!
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:
1
# applied
2
deployment.apps/podinfo
3
horizontalpodautoscaler.autoscaling/podinfo
4
canary.flagger.app/podinfo
5
6
# generated
7
deployment.apps/podinfo-primary
8
horizontalpodautoscaler.autoscaling/podinfo-primary
9
service/podinfo
10
service/podinfo-canary
11
service/podinfo-primary
12
httproutes.gateway.networking.k8s.io/podinfo
Copied!

Expose the app outside the cluster

Find the external address of Contour's Envoy load balancer:
1
export ADDRESS="$(kubectl -n projectcontour get svc/envoy -ojson \
2
| jq -r ".status.loadBalancer.ingress[].hostname")"
3
echo $ADDRESS
Copied!
Configure your DNS server with a CNAME record (AWS) or A record (GKE/AKS/DOKS) and point a domain e.g. localproject.contour.io 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 Contour with TLS certificates.
If you're using a local cluster via kind/k3s you can port forward the Envoy LoadBalancer service:
1
kubectl port-forward -n projectcontour svc/envoy 8080:80
Copied!
Now you can access podinfo via curl -H "Host: localproject.contour.io" localhost:8080

Automated canary promotion

Trigger a canary deployment by updating the container image:
1
kubectl -n test set image deployment/podinfo \
2
podinfod=stefanprodan/podinfo:6.0.1
Copied!
Flagger detects that the deployment revision changed and starts a new rollout:
1
kubectl -n test describe canary/podinfo
2
3
Status:
4
Canary Weight: 0
5
Failed Checks: 0
6
Phase: Succeeded
7
Events:
8
Type Reason Age From Message
9
---- ------ ---- ---- -------
10
Normal Synced 3m flagger New revision detected podinfo.test
11
Normal Synced 3m flagger Scaling up podinfo.test
12
Warning Synced 3m flagger Waiting for podinfo.test rollout to finish: 0 of 1 updated replicas are available
13
Normal Synced 3m flagger Advance podinfo.test canary weight 5
14
Normal Synced 3m flagger Advance podinfo.test canary weight 10
15
Normal Synced 3m flagger Advance podinfo.test canary weight 15
16
Normal Synced 2m flagger Advance podinfo.test canary weight 20
17
Normal Synced 2m flagger Advance podinfo.test canary weight 25
18
Normal Synced 1m flagger Advance podinfo.test canary weight 30
19
Normal Synced 1m flagger Advance podinfo.test canary weight 35
20
Normal Synced 55s flagger Advance podinfo.test canary weight 40
21
Normal Synced 45s flagger Advance podinfo.test canary weight 45
22
Normal Synced 35s flagger Advance podinfo.test canary weight 50
23
Normal Synced 25s flagger Copying podinfo.test template spec to podinfo-primary.test
24
Warning Synced 15s flagger Waiting for podinfo-primary.test rollout to finish: 1 of 2 updated replicas are available
25
Normal Synced 5s flagger Promotion completed! Scaling down podinfo.test
Copied!
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 how Flagger progressively changes the weights of the HTTPRoute object that is attahed to the Gateway with:
1
watch kubectl get httproute -n test podinfo -o=jsonpath='{.spec.rules}'
Copied!
You can monitor all canaries with:
1
watch kubectl get canaries --all-namespaces
2
3
NAMESPACE NAME STATUS WEIGHT LASTTRANSITIONTIME
4
test podinfo Progressing 15 2022-01-16T14:05:07Z
5
prod frontend Succeeded 0 2022-01-15T16:15:07Z
6
prod backend Failed 0 2022-01-14T17:05:07Z
Copied!

Automated rollback

During the canary analysis you can generate HTTP 500 errors and high latency to test if Flagger pauses the rollout.
Trigger another canary deployment:
1
kubectl -n test set image deployment/podinfo \
2
podinfod=stefanprodan/podinfo:6.0.2
Copied!
Exec into the load tester pod with:
1
kubectl -n test exec -it flagger-loadtester-xx-xx sh
Copied!
Generate HTTP 500 errors:
1
watch curl http://podinfo-canary:9898/status/500
Copied!
Generate latency:
1
watch curl http://podinfo-canary:9898/delay/1
Copied!
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.
1
kubectl -n test describe canary/podinfo
2
3
Status:
4
Canary Weight: 0
5
Failed Checks: 10
6
Phase: Failed
7
Events:
8
Type Reason Age From Message
9
---- ------ ---- ---- -------
10
Normal Synced 3m flagger Starting canary deployment for podinfo.test
11
Normal Synced 3m flagger Advance podinfo.test canary weight 5
12
Normal Synced 3m flagger Advance podinfo.test canary weight 10
13
Normal Synced 3m flagger Advance podinfo.test canary weight 15
14
Normal Synced 3m flagger Halt podinfo.test advancement error rate 69.17% > 1%
15
Normal Synced 2m flagger Halt podinfo.test advancement error rate 61.39% > 1%
16
Normal Synced 2m flagger Halt podinfo.test advancement error rate 55.06% > 1%
17
Normal Synced 2m flagger Halt podinfo.test advancement error rate 47.00% > 1%
18
Normal Synced 2m flagger (combined from similar events): Halt podinfo.test advancement error rate 38.08% > 1%
19
Warning Synced 1m flagger Rolling back podinfo.test failed checks threshold reached 10
20
Warning Synced 1m flagger Canary failed! Scaling down podinfo.test
Copied!

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.
Flagger A/B Testing Stages
Create a canary custom resource (replace "loaclproject.contour.io" with your own domain):
1
apiVersion: flagger.app/v1beta1
2
kind: Canary
3
metadata:
4
name: podinfo
5
namespace: test
6
spec:
7
# deployment reference
8
targetRef:
9
apiVersion: apps/v1
10
kind: Deployment
11
name: podinfo
12
# the maximum time in seconds for the canary deployment
13
# to make progress before it is rollback (default 600s)
14
progressDeadlineSeconds: 60
15
# HPA reference (optional)
16
autoscalerRef:
17
apiVersion: autoscaling/v2beta2
18
kind: HorizontalPodAutoscaler
19
name: podinfo
20
service:
21
# service port number
22
port: 9898
23
# container port number or name (optional)
24
targetPort: 9898
25
# Gateway API HTTPRoute host names
26
hosts:
27
- localproject.contour.io
28
# Reference to the Gateway that the generated HTTPRoute would attach to.
29
gatewayRefs:
30
- name: contour
31
namespace: projectcontour
32
analysis:
33
# schedule interval (default 60s)
34
interval: 1m
35
# max number of failed metric checks before rollback
36
threshold: 5
37
# max traffic percentage routed to canary
38
# percentage (0-100)
39
maxWeight: 50
40
# canary increment step
41
# percentage (0-100)
42
stepWeight: 10
43
metrics:
44
- name: error-rate
45
# max error rate (5xx responses)
46
# percentage (0-100)
47
templateRef:
48
name: error-rate
49
namespace: flagger-system
50
thresholdRange:
51
max: 1
52
interval: 1m
53
- name: latency
54
templateRef:
55
name: latency
56
namespace: flagger-system
57
# seconds
58
thresholdRange:
59
max: 0.5
60
interval: 30s
61
# testing (optional)
62
webhooks:
63
- name: smoke-test
64
type: pre-rollout
65
url: http://flagger-loadtester.test/
66
timeout: 15s
67
metadata:
68
type: bash
69
cmd: "curl -sd 'anon' http://podinfo-canary.test:9898/token | grep token"
70
- name: load-test
71
url: http://flagger-loadtester.test/
72
timeout: 5s
73
metadata:
74
cmd: "hey -z 2m -q 10 -c 2 -host localproject.contour.io -H 'X-Canary: insider' http://envoy.projectcontour/"
Copied!
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:
1
kubectl apply -f ./podinfo-ab-canary.yaml
Copied!
Trigger a canary deployment by updating the container image:
1
kubectl -n test set image deployment/podinfo \
2
podinfod=stefanprodan/podinfo:6.0.3
Copied!
Flagger detects that the deployment revision changed and starts a new rollout:
1
kubectl -n test describe canary/abtest
2
3
Status:
4
Failed Checks: 0
5
Phase: Succeeded
6
Events:
7
Type Reason Age From Message
8
---- ------ ---- ---- -------
9
Normal Synced 3m flagger New revision detected podinfo.test
10
Normal Synced 3m flagger Scaling up podinfo.test
11
Warning Synced 3m flagger Waiting for podinfo.test rollout to finish: 0 of 1 updated replicas are available
12
Normal Synced 3m flagger Advance podinfo.test canary iteration 1/10
13
Normal Synced 3m flagger Advance podinfo.test canary iteration 2/10
14
Normal Synced 3m flagger Advance podinfo.test canary iteration 3/10
15
Normal Synced 2m flagger Advance podinfo.test canary iteration 4/10
16
Normal Synced 2m flagger Advance podinfo.test canary iteration 5/10
17
Normal Synced 1m flagger Advance podinfo.test canary iteration 6/10
18
Normal Synced 1m flagger Advance podinfo.test canary iteration 7/10
19
Normal Synced 55s flagger Advance podinfo.test canary iteration 8/10
20
Normal Synced 45s flagger Advance podinfo.test canary iteration 9/10
21
Normal Synced 35s flagger Advance podinfo.test canary iteration 10/10
22
Normal Synced 25s flagger Copying podinfo.test template spec to podinfo-primary.test
23
Warning Synced 15s flagger Waiting for podinfo-primary.test rollout to finish: 1 of 2 updated replicas are available
24
Normal Synced 5s flagger Promotion completed! Scaling down podinfo.test
Copied!
The above procedures can be extended with custom metrics checks, webhooks, manual promotion approval and Slack or MS Teams notifications.