Table of Contents

Horizontal Pod Auto-Scaling (HPA)

https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/

In Kubernetes, a HorizontalPodAutoscaler automatically updates a workload resource (such as a Deployment or StatefulSet), with the aim of automatically scaling capacity to match demand.

Info

For HPA to work resources has to be implemented and metrics-server

php-apache-deployment.yaml

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: php-apache
spec:
  selector:
    matchLabels:
      run: php-apache
  replicas: 1
  template:
    metadata:
      labels:
        run: php-apache
    spec:
      containers:
      - name: php-apache
        image: registry.k8s.io/hpa-example
        ports:
        - containerPort: 80
        resources:          # <--- mandatory (base line)
          limits:
            cpu: 500m
            memory: 32Mi
          requests:
            cpu: 200m      #  <-- metric to determine cpu scale
            memory: 32Mi   #  <-- metric to determine memory scale
            
---
apiVersion: v1
kind: Service
metadata:
  name: php-apache
  labels:
    run: php-apache
spec:
  ports:
  - port: 80
  selector:
    run: php-apache
 
kubectl apply -f php-apache-deployment.yaml
 

Create HPA with threshold of 50%

kubectl autoscale deployment php-apache --cpu='50%' --min=1 --max=10
 

Implement some monitors (tmux) on different panels or windows

watch kubectl get hpa php-apache
watch kubectl get pods -o wide
watch kubectl top pods
watch kubectl top nodes

Create some load

# Run this in a separate terminal so that the load generation continues and you can carry on with the rest of the steps
kubectl run -it load-generator --rm --image=alpine --restart=Never -- /bin/sh -c "while sleep 0.01; do /usr/bin/time -f' time:%E' wget -q -O- http://php-apache; done"
 

Kubernetes deployment strategies

  • recreate: terminate the old version and release the new one
  • rolling-update: release a new version on a rolling update fashion, one after the other

img-recreate_rolling.gif

Recreate strategies

spec:
  replicas: 6
  strategy:
    type: Recreate
    

RollingUpdate strategies

spec:
  replicas: 6
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 25%         # how many pods we can add at a time or %
      maxUnavailable: 25%   # maxUnavailable define how many pods 
					        # can be unavailable during the rolling update
	

Create a bash consumer

while true; do code=$(curl -s -o /dev/null --max-time 0.1 -w "%{http_code}" http://192.168.49.2:<port>); if [ "$code" -ne 200 ]; then echo "⚠️  Status: $code"; else echo "✅ Status: $code"; fi; sleep 0.1; done

Deployment Roll out’s

# restart deployment
kubectl rollout restart deployment/php-apache
 
# View status of restart
kubectl rollout status deployment/php-apache -w
 
# Check the history of deployments including the revision  
kubectl rollout history deployment/php-apache
 
# Annotate 
kubectl annotate deployments.apps/php-apache \
	kubernetes.io/change-cause="problems in nodes"
 
# Change image of deployment  
kubectl set image deploy/php-apache php-apache=docker.io/nginxdemos/hello:plain-text
 
# Annotate 
kubectl annotate deployments.apps/php-apache \
	kubernetes.io/change-cause="fix image to hello"
	
# Rolling restart of the "frontend" deployment  
kubectl rollout restart deployment/php-apache
 
# Rolling back last  
kubectl rollout undo deployment/php-apache
 
# Rolling back to revision
kubectl rollout undo deployment/php-apache --to-revision=2
 

Deployment Strategies

https://github.com/ContainerSolutions/k8s-deployment-strategies/tree/master

  • ab-testing
  • blue-green
  • canary
  • shadow

Blue-Green Deploys

blue-green: release a new version alongside the old version then switch traffic

https://github.com/ContainerSolutions/k8s-deployment-strategies/tree/master/blue-green/single-service

img-blue-green.gif

Create the Namespace

First, create a namespace specifically for the Blue-Green demo. This keeps the Blue and Green environments separate from other resources in your cluster.

kubectl create namespace blue-green-demo
 

Create the Blue Environment

Now, create the initial “Blue” deployment and expose it via a Service within the newly created namespace.

Create the Blue Deployment (blue-deployment.yaml):

apiVersion: v1
kind: Service
metadata:
  name: my-app
  namespace: blue-green-demo
  labels:
    app: my-app
spec:
  type: NodePort
  ports:
  - name: http
    port: 80
    targetPort: http
  # Select my-app v1
  selector:
    app: my-app
    version: v1
 
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app-v1
  namespace: blue-green-demo
  labels:
    app: my-app
spec:
  replicas: 3
  selector:
    matchLabels:
      app: my-app
      version: v1
  template:
    metadata:
      labels:
        app: my-app
        version: v1
    spec:
      containers:
      - name: my-app
        image: containersol/k8s-deployment-strategies
        ports:
        - name: http
          containerPort: 8080
        - name: probe
          containerPort: 8086
        env:
        - name: VERSION
          value: v1
        livenessProbe:
          httpGet:
            path: /live
            port: probe
          initialDelaySeconds: 5
          periodSeconds: 5
        readinessProbe:
          httpGet:
            path: /ready
            port: probe
          periodSeconds: 5
        resources:
          limits:
            cpu: "100m"
            memory: "256Mi"
          requests:
            cpu: "100m"
            memory: "256Mi"
 

Apply the configuration:

kubectl apply -f blue-deployment.yaml

Create the Green Environment

The Green environment is identical to Blue but uses a different image tag (or version) to simulate a new release.

Create the Green Deployment (green-deployment.yaml):

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app-v2
  namespace: blue-green-demo
  labels:
    app: my-app
spec:
  replicas: 3
  selector:
    matchLabels:
      app: my-app
      version: v2
  template:
    metadata:
      labels:
        app: my-app
        version: v2
    spec:
      containers:
      - name: my-app
        image: containersol/k8s-deployment-strategies
        ports:
        - name: http
          containerPort: 8080
        - name: probe
          containerPort: 8086
        env:
        - name: VERSION
          value: v2
        livenessProbe:
          httpGet:
            path: /live
            port: probe
          initialDelaySeconds: 5
          periodSeconds: 5
        readinessProbe:
          httpGet:
            path: /ready
            port: probe
          periodSeconds: 5
        resources:
          limits:
            cpu: "100m"
            memory: "256Mi"
          requests:
            cpu: "100m"
            memory: "256Mi"
 

Apply the configuration:

kubectl apply -f green-deployment.yaml

Verify the Deployment

Check the pods in both environments to ensure they are running.

kubectl get pods -n blue-green-demo

You should see two blue-app pods and two green-app pods.

Traffic Switching (The “Switch”)

In a Blue-Green strategy, both environments run simultaneously. Traffic is switched by updating the Service selector.

Option A: Manual Switch (Quick Test)
Update the blue-service to point to the green pods.

kubectl patch service -n blue-green-demo my-app -p '{"spec":{"selector":{"version":"v2"}}}'
 

Consumer

service=$(minikube service -n blue-green-demo my-app --url)
while sleep 0.1; do curl "$service"; done
 

Cleanup

When you are done testing, you can delete the resources:

kubectl delete ns blue-green-demo
 
# or
 
kubectl delete all -l app=my-app

“

A/B Deploys

a/b testing: release a new version to a subset of users in a precise way (HTTP headers, cookie, weight, etc.). A/B testing is really a technique for making business decisions based on statistics but we will briefly describe the process

https://github.com/ContainerSolutions/k8s-deployment-strategies/tree/master/ab-testing

Define the Application Versions

Create two identical deployments, app-v1 (control group) and app-v2 (experimental group), but with different image tags or configurations.

app-v1.yaml (Control Group)

apiVersion: apps/v1
kind: Deployment
metadata:
  name: app-v1
  labels:
    app: webcounter
    version: v1
spec:
  replicas: 2
  selector:
    matchLabels:
      app: webcounter
      version: v1
  template:
    metadata:
      labels:
        app: webcounter
        version: v1
    spec:
      containers:
        - name: webcounter
          image: cfreire70/webcounter
          ports:
            - containerPort: 5000
---
apiVersion: v1
kind: Service
metadata:
  name: app-v1-svc
spec:
  selector:
    app: webcounter
    version: v1
  ports:
    - protocol: TCP
      port: 80
      targetPort: 5000

app-v2.yaml (Experimental Group)

apiVersion: apps/v1
kind: Deployment
metadata:
  name: app-v2
  labels:
    app: webcounter
    version: v2
spec:
  replicas: 2
  selector:
    matchLabels:
      app: webcounter
      version: v2
  template:
    metadata:
      labels:
        app: webcounter
        version: v2
    spec:
      containers:
	  - name: webcounter
		image: cfreire70/my-webcounter
		ports:
		  - containerPort: 5000
---
apiVersion: v1
kind: Service
metadata:
  name: app-v2-svc
spec:
  selector:
    app: webcounter
    version: v2
  ports:
    - protocol: TCP
      port: 80
      targetPort: 5000

Create a Load Balancer Service

Create a single external service that routes traffic to both deployments. We will use weight-based routing (via annotations) to simulate the A/B split.

load-balancer.yaml

apiVersion: v1
kind: Service
metadata:
  name: app-lb
  annotations:
    # Example: Route 50% to v1 and 50% to v2
    # Note: Standard K8s Services don't support direct weight annotations.
    # We will use a custom solution or Istio/Ingress for real traffic splitting.
    # For this example, we'll use a simple round-robin or manual header check.
    # To achieve true A/B testing, we typically use an Ingress Controller.
    kubernetes.io/ingress.class: nginx
spec:
  type: ClusterIP
  selector:
    app: webcounter
  ports:
    - protocol: TCP
      port: 80
      targetPort: 5000

For true A/B testing based on HTTP headers (e.g., X-Test-Group: control or experimental), use an Ingress resource with an annotation that supports header-based routing.

ingress-ab.yaml

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: app-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
    # Example: Route based on header 'X-Test-Group'
    # This requires an Ingress Controller that supports header-based routing
    nginx.ingress.kubernetes.io/enable-cors: "true"
spec:
  rules:
    - http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: app-lb
                port:
                  number: 80

Simulate A/B Testing in Minikube

Since Minikube’s default Ingress controller might not support complex header routing out-of-the-box, you can simulate the split manually using a ConfigMap and a Sidecar or a simple Shell Script to redirect traffic.

Option A: Using a ConfigMap for Header Inspection (Manual)
Create a ConfigMap to store the routing logic.

configmap-routing.yaml

apiVersion: v1
kind: ConfigMap
metadata:
  name: routing-config
data:
  # Define the split ratio
  split-ratio: "50/50"
  # Define header names to check
  header-name: "X-Test-Group"

Verify the Deployment

  1. Deploy the resources:

    kubectl apply -f app-v1.yaml
    kubectl apply -f app-v2.yaml
    kubectl apply -f ingress-ab.yaml
  2. Check the pods:

    kubectl get pods
  3. Test the routing:

    • Access the service via minikube service app-lb --url.
    • Send requests with different headers:
      curl -H "X-Test-Group: control" http://<service-url>/
      curl -H "X-Test-Group: experimental" http://<service-url>/

Rollback

If the A/B test reveals issues, you can easily rollback by:

  1. Deleting the app-v2 deployment.
  2. Updating the Ingress rules to route all traffic to app-v1.
  3. Or simply scaling app-v2 to zero.
kubectl scale deployment app-v2 --replicas=0
kubectl delete deployment app-v2

Canary Deploys

canary: release a new version to a subset of users, then proceed to a full rollout in time

https://github.com/ContainerSolutions/k8s-deployment-strategies/tree/master/canary/native