# Deployment patterns: rolling, blue-green, canary, GitOps

Ship new versions without downtime: a rolling update, a bad release caught and undone, a blue-green switch, a canary taking a share of traffic, and how GitOps and CI/CD automate it.

Course: [Kubernetes & Helm](https://devops.rajeev.pro/courses/kubernetes), lesson 14. About 35 minutes, intermediate. Source: https://devops.rajeev.pro/courses/kubernetes/14-deployment-patterns

## What you will learn

- Run a rolling update and undo a bad one with kubectl rollout
- Switch all traffic between two versions at once with blue-green
- Send a share of traffic to a new version with a canary
- Explain GitOps with Argo CD and where CI/CD fits

> **Lab status.** **Verified lab:** a rolling update, a broken release undone with rollout undo, a blue-green switch and a Pod-count canary, on the course's EKS cluster. The output shown is real. <br />**Code walkthrough:** Argo CD and the CI pipeline (manifests and workflow shown, not run in the lab). <br />**Cloud lab:** none needed; works on kind.

Releasing is when most outages happen. Kubernetes gives you a safe default, the rolling update, and the pieces
to build the other common patterns. This lesson runs each one with the shop-web images: `v1`, `v2`, and
`v3-broken`, which crashes on start.

## Rolling updates and rollbacks

Changing a Deployment's image starts a **rolling update**: new Pods come up, and old ones go away only once
new ones are ready.

> **Figure.** Animation with the lab Deployment shop-web: 2 replicas and the default 25 percent strategy, which works out to maxSurge 1 and maxUnavailable 0. set image v2 creates ReplicaSet 57f494cdcb: it starts one v2 Pod, and only when that Pod is Ready does the old v1 ReplicaSet remove a Pod; then the second v2 Pod starts and the last v1 Pod goes. The Pod count goes 2, 3, 2, 3, 2 and never drops below 2 Ready. set image v3-broken creates ReplicaSet 555d869f9: its one Pod goes into CrashLoopBackOff and never gets Ready, so no v2 Pod is removed and READY stays 2/2. kubectl rollout undo scales the broken ReplicaSet to 0.
>
> Each image change makes a new ReplicaSet. The CI/CD course shows the same rollout from the pipeline's side.

```text
$ kubectl set image deployment/shop-web web=626159997645.dkr.ecr.ap-south-1.amazonaws.com/shop-web:v2
deployment.apps/shop-web image updated
$ kubectl rollout status deployment/shop-web --timeout=180s
Waiting for deployment "shop-web" rollout to finish: 1 out of 2 new replicas have been updated...
Waiting for deployment "shop-web" rollout to finish: 1 old replicas are pending termination...
deployment "shop-web" successfully rolled out
$ kubectl run c --image=busybox:1.37 --restart=Never --rm -i --quiet -- wget -qO- http://shop-web/api
{"version": "v2", "pod": "shop-web-57f494cdcb-ltvkc", "greeting": "Hello from Kubernetes", "uptime_seconds": 11}
```

Now a bad release:

```text
$ kubectl set image deployment/shop-web web=626159997645.dkr.ecr.ap-south-1.amazonaws.com/shop-web:v3-broken
$ kubectl rollout status deployment/shop-web --timeout=60s
Waiting for deployment "shop-web" rollout to finish: 1 out of 2 new replicas have been updated...
error: timed out waiting for the condition
$ kubectl get pods -l app=shop-web
NAME                        READY   STATUS             RESTARTS      AGE
shop-web-555d869f9-7fzmm    0/1     CrashLoopBackOff   3 (34s ago)   67s
shop-web-57f494cdcb-ltvkc   1/1     Running            0             86s
shop-web-57f494cdcb-tckth   1/1     Running            0             79s
$ kubectl get deployment shop-web
NAME       READY   UP-TO-DATE   AVAILABLE   AGE
shop-web   2/2     1            2           51m
```

This is the rolling update protecting you. The one new Pod never became ready, so the Deployment never removed
an old one: `READY 2/2`, users still on v2. The readiness probe (lesson 4) is what makes this work; without it,
the crashing Pod could have been counted as ready. Undo:

```text
$ kubectl rollout undo deployment/shop-web
Warning: resource deployments/shop-web was previously managed with 'kubectl apply'. Rolling back will not update the kubectl.kubernetes.io/last-applied-configuration annotation, ...
deployment.apps/shop-web rolled back
$ kubectl rollout status deployment/shop-web --timeout=180s
deployment "shop-web" successfully rolled out
$ kubectl get pods -l app=shop-web -o custom-columns=POD:.metadata.name,IMAGE:.spec.containers[0].image
POD                         IMAGE
shop-web-57f494cdcb-ltvkc   626159997645.dkr.ecr.ap-south-1.amazonaws.com/shop-web:v2
shop-web-57f494cdcb-tckth   626159997645.dkr.ecr.ap-south-1.amazonaws.com/shop-web:v2
```

Read that warning: `rollout undo` changes the cluster but not your YAML. The next `kubectl apply` of the old
file would bring v3-broken back. In real teams the fix goes into Git (or the Helm values), which is the GitOps
idea below. Tune the pace with `maxSurge` and `maxUnavailable` in the Deployment's strategy.

## Blue-green

Run the new version **next to** the old one, test it, then move all traffic at once. Two Deployments with a
`color` label, and one Service choosing between them:

```yaml
# 14-bluegreen.yaml (excerpt)
kind: Deployment
metadata:
  name: shop-blue # image shop-web:v1, labels app=shop, color=blue
---
kind: Deployment
metadata:
  name: shop-green # image shop-web:v2, labels app=shop, color=green
---
apiVersion: v1
kind: Service
metadata:
  name: shop
spec:
  selector: { app: shop, color: blue } # live version
  ports:
    - port: 80
      targetPort: 8080
```

```text
$ kubectl run c --image=busybox:1.37 --restart=Never --rm -i --quiet -- wget -qO- http://shop/api
{"version": "v1", "pod": "shop-blue-55c7dcf55f-jth8r", "greeting": "Hello from Kubernetes", "uptime_seconds": 6}
$ kubectl patch service shop -p '{"spec":{"selector":{"app":"shop","color":"green"}}}'
service/shop patched
$ kubectl run c --image=busybox:1.37 --restart=Never --rm -i --quiet -- wget -qO- http://shop/api
{"version": "v2", "pod": "shop-green-5c46897fcf-2r9kg", "greeting": "Hello from Kubernetes", "uptime_seconds": 17}
```

One patch, and every new request goes to v2. Rolling back is the same patch with `blue`. The cost: both versions
run in full during the switch, so you pay for double capacity, and both must work with the same database.

> **Figure.** Two panels. Before the patch: the Service shop has selector app shop, color blue, so all traffic goes to Deployment shop-blue, two Pods on shop-web v1, while shop-green, two Pods on v2, runs with no traffic, ready to test. After kubectl patch service shop sets color green: all traffic goes to shop-green v2, and shop-blue keeps running with no traffic, kept for rollback.

## Canary

Send a **small share** of traffic to the new version first and watch its errors before going further. The
simplest form uses Pod counts: remove `color` from the selector so the Service matches both, then run 3 blue and
1 green.

```text
$ kubectl patch service shop -p '{"spec":{"selector":{"app":"shop","color":null}}}'
$ kubectl scale deployment shop-blue --replicas=3
$ kubectl scale deployment shop-green --replicas=1
$ for i in $(seq 1 20); do wget -qO- http://shop/api; done | grep -o '"version": "v[0-9]"' | sort | uniq -c
     28 "version": "v1"
     12 "version": "v2"
```

The counts are doubled because of a kubectl quirk in the lab: the client Pod's attach failed and kubectl
replayed its logs, so every line appears twice. The real split was **14 v1 and 6 v2** out of 20, about the 25%
that one Pod in four gives (random spread over a small sample). If v2's error rate stays flat, scale green up
and blue down until blue is gone.

> **Figure.** Animation. The Service shop selects app shop with no color label, so requests flow to all four Pods: three shop-blue Pods on v1 and one shop-green Pod on v2, roughly one request in four going to v2. The lab count over 20 requests: 14 to v1 and 6 to v2. If v2 errors stay flat, scale green up and blue down: 3 to 1, then 2 to 2, then 0 to 4.

Pod-count canaries are coarse: you can't do 1% without 99 old Pods. For exact weights, use an ingress or
Gateway API route with weights, a service mesh, or **Argo Rollouts**, which also checks metrics and rolls back
automatically when the canary looks bad.

## GitOps

In every example above a person typed commands. **GitOps** makes Git the source of truth: the desired state of
the cluster lives in a repository, and a controller in the cluster keeps the cluster matching it. Change Git,
and the cluster follows; change the cluster by hand, and the controller puts it back.

> **Figure.** Two panels. Push, CI deploys: a CI job holds a kubeconfig with cluster credentials and runs kubectl apply into the cluster. What hurts: CI is a key to production, hand edits drift from Git unseen, and knowing what runs means asking the cluster; every command in this lesson so far works this way. Pull, GitOps with Argo CD: the repository shop-deploy holds values-prod.yaml with image.tag v2; Argo CD runs inside the cluster, pulls from Git, compares it with the cluster and keeps namespace shop equal to Git. You get: CI never holds cluster keys, selfHeal undoes hand edits, prune deletes what left Git, and history is the git log. A release is a pull request, a rollback is git revert.

The CI/CD course [animates the sync loop](/courses/cicd/10-gitops), including self-heal undoing a manual
scale.

**Argo CD** is the most common controller. An `Application` points it at a path in a repo:

```yaml
# shop-app.yaml (Argo CD Application)
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: shop
  namespace: argocd
spec:
  project: default
  source:
    repoURL: https://github.com/<you>/shop-deploy
    path: helm/shop
    targetRevision: main
    helm:
      valueFiles: [values-prod.yaml]
  destination:
    server: https://kubernetes.default.svc
    namespace: shop
  syncPolicy:
    automated:
      prune: true # delete what was removed from Git
      selfHeal: true # undo manual changes
```

A release is then a pull request that changes `image.tag` in `values-prod.yaml`. A rollback is reverting that
commit, which fixes the problem the `rollout undo` warning pointed at: Git and the cluster never disagree for
long. Every change has an author, a review and a history. Flux is the other main GitOps tool and works the same
way.

## CI/CD integration

The pieces join up like this:

1. **CI** (GitHub Actions, GitLab CI, Jenkins) runs tests, builds the image, tags it with the commit SHA, scans
   it and pushes it to the registry (ECR in this course).
2. CI then updates the image tag in the deployment repo (or opens a PR for production).
3. **CD**, Argo CD here, sees the change and syncs the cluster. The Deployment does a rolling update, or Argo
   Rollouts runs a canary.

> **Figure.** Numbered flow. 1: a developer merges a pull request in the app repository shop-web. 2: CI on GitHub Actions tests, builds and scans the image, tags it sha-commit and pushes it to ECR. 3: CI commits image.tag sha-commit to values-prod.yaml in the shop-deploy repository, as a pull request for production. 4: Argo CD inside the EKS cluster pulls from Git, sees the change and syncs. 5: the Deployment in namespace shop does a rolling update or an Argo Rollouts canary. 6: the nodes pull the image from ECR. There is no arrow from CI into the cluster: CI has no cluster keys.

CI never needs cluster credentials in this setup, which is a real security win: the cluster pulls from Git
instead of CI pushing into the cluster.

## Mission: Release, break, switch and split

Roll shop-web to v2, then to v3-broken, and undo it. Apply the blue-green manifest, switch from blue to green and back, then run a 3:1 canary and count versions over 40 requests. Record each step.

- You need: The shop-web images and 14-bluegreen.yaml
- You'll have: ~/releases.txt

```sh
$ kubectl set image deployment/shop-web web=<registry>/shop-web:v2 && kubectl rollout status deployment/shop-web
$ kubectl set image deployment/shop-web web=<registry>/shop-web:v3-broken
$ kubectl rollout status deployment/shop-web --timeout=60s >> ~/releases.txt 2>&1
$ kubectl get pods -l app=shop-web >> ~/releases.txt
$ kubectl rollout undo deployment/shop-web && kubectl rollout status deployment/shop-web
$ kubectl apply -f 14-bluegreen.yaml
$ kubectl patch service shop -p '{"spec":{"selector":{"app":"shop","color":"green"}}}'
$ kubectl patch service shop -p '{"spec":{"selector":{"app":"shop","color":null}}}'
$ kubectl scale deployment shop-blue --replicas=3; kubectl scale deployment shop-green --replicas=1
$ kubectl run c --image=busybox:1.37 --restart=Never --rm -i --quiet -- sh -c 'for i in $(seq 1 40); do wget -qO- http://shop/api; echo; done' | grep -o '"version": "v[0-9]"' | sort | uniq -c >> ~/releases.txt
$ kubectl delete -f 14-bluegreen.yaml
```

Expect a timeout for v3-broken with READY still 2/2, and roughly three v1 requests for every v2.

## Try it

- Update shop-web to v2 and watch `kubectl rollout status`.
- Update to v3-broken, see the rollout stall, and run `kubectl rollout undo`.
- Apply the blue-green manifest and switch the Service selector.
- Scale blue to 3 and green to 1 and count versions over 20 requests.
- Do the mini mission and keep `~/releases.txt`.

## Quiz

1. A rolling update to a crashing image stalls with 1 of 2 new replicas updated. Is the app down?
   - Yes, all Pods were replaced
   - **No; the old Pods keep running because the new one never became ready. Undo the rollout** (answer)
   - Only if there's no Service
   Why: In the lab, READY stayed 2/2 with two v2 Pods serving while the v3-broken Pod crash-looped.

2. What makes blue-green switch traffic all at once?
   - Deleting the old Pods
   - **Changing the Service selector from color=blue to color=green** (answer)
   - Restarting the Service
   Why: Both versions run side by side, and the Service points at one of them. Switching back is the same patch in reverse.

3. With 3 blue Pods and 1 green Pod behind one Service, roughly what share of requests reach green?
   - 50%
   - **About 25%, because traffic spreads across Pods** (answer)
   - 0% until promoted
   Why: The lab saw 6 of 20 requests on v2. Pod-count canaries are coarse; a mesh or ingress weights give exact percentages.

## Resources

- [Deployments, rolling update and rollback](https://kubernetes.io/docs/concepts/workloads/controllers/deployment/) (Kubernetes)
- [Argo CD](https://argo-cd.readthedocs.io/en/stable/) (Argo CD)
- [Argo Rollouts](https://argoproj.github.io/rollouts/) (Argo)
- [OpenGitOps principles](https://opengitops.dev/) (OpenGitOps)
