Blue-Green Deployment in K8s

Blue-Green deployment is an application rollout model that progressively directs user traffic from the previous version of an application or service to a new version of it, while both versions are running in parallel for a limited amount of time.

not ready

The old version is usually named Blue, while the new version is name Green. Once the Green version is fully tested by the development team, user traffic can be redirected from Blue version to the Green. The Blue version can still run for quite some time making it fairly easy to rollback in case the Green version has issues.

redirected

Let’s see how we can do that in Kubernetes. Lets say we have the following Deployment:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp
spec:
  selector:
    matchLabels:
      app: version1
  template:
    metadata:
      labels:
        app: version1
    spec:
      containers:
      - name: myapp
        image: myapp:version1
        resources:
          limits:
            memory: "128Mi"
            cpu: "500m"

kubectl create -f deployment1.yml

That is our initial (blue) deployed version of the app. Our running container is exposed using a service

apiVersion: v1
kind: Service
metadata:
  name: myapp
spec:
  selector:
    app: version1
  ports:
  - port: 8080
    targetPort: 8080

kubectl create -f service.yml

In this service we have the selector target the pods with label app:version1. To create a new (Green) version of our app, we can create a second deployment with different labels.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp
spec:
  selector:
    matchLabels:
      app: version2
  template:
    metadata:
      labels:
        app: version2
    spec:
      containers:
        - name: myapp
          image: myapp:version2
          resources:
            limits:
              memory: '128Mi'
              cpu: '500m'

kubectl create -f deployment2.yml

Once we are sure that these pods are ready and do not have any issue we can change the labels in our Service to direct traffic to the newly created (green) pods.

apiVersion: v1
kind: Service
metadata:
  name: myapp
spec:
  selector:
    app: version2
  ports:
    - port: 8080
      targetPort: 8080

And trigger the changes with kubectl apply -f service.yml

Once we verify that we dont have to rollback we can delete the pods of the Deployment one.

kubectl delete -f deployment1.yml

Further reading on Blue/Green Deployment

Published 2 Jan 2021

Engineering Manager. Opinions are my own and not necessarily the views of my employer.
Avraam Mavridis on Twitter