Docker & Kubernetes

Canary Releases on Plain Kubernetes: How the Traffic Split Really Works

A canary release sends a small share of production traffic to a new version before everyone gets it. If error rates or latency get worse, you remove the canary and only that slice of users was affected.

You can run a basic canary on Kubernetes with nothing but two Deployments and one Service. This guide sets that up step by step, explains exactly how traffic gets split (and why the split is rougher than it looks), and covers when to move to Argo Rollouts, Flagger, or Gateway API traffic splitting for precise, automated canaries.

Understanding Canary Deployments

A canary deployment is a strategy where a new version of your application (the "canary") is deployed alongside the existing stable version (the "baseline" or "production") and traffic is gradually shifted to the canary. Initially, only a small percentage of user traffic is routed to the new version. This small exposure acts like a "canary in a coal mine" – if the canary version exhibits errors, performance degradation, or unexpected behavior, it can be quickly rolled back or isolated before it impacts the majority of users. If the canary performs well, traffic can be progressively increased until the new version completely replaces the old one.

Canaries catch problems that tests and staging miss, such as real traffic patterns, production data and production-only integrations, while limiting how many users see a bad release.

Prerequisites

Before we dive into the steps, ensure you have the following installed and configured:

  • Docker Desktop (or Docker Engine): For building your application images.
  • Kubernetes Cluster: A local cluster like Minikube or Kind is perfect for this tutorial. Alternatively, any cloud-managed Kubernetes cluster (EKS, GKE, AKS) will work.
  • kubectl: The Kubernetes command-line tool, configured to connect to your cluster.

Step-by-Step: Implementing Canary Deployments

We'll use a simple Node.js application that displays its version to illustrate the process.

1. Prepare Your Application Docker Images

First, let's create two versions of our application: v1.0.0 (baseline) and v1.1.0 (canary).

Create a file named app.js for v1.0.0:

JavaScript
// app.js for v1.0.0
const express = require('express');
const app = express();
const port = 3000;
const VERSION = 'v1.0.0 - Baseline';

app.get('/', (req, res) => {
  res.send(`Hello from ${VERSION}!\n`);
});

app.get('/healthz', (req, res) => res.send('ok'));

app.listen(port, () => {
  console.log(`App running on port ${port} - ${VERSION}`);
});

And a Dockerfile:

Dockerfile
# Dockerfile
FROM node:22-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY app.js .
USER node
EXPOSE 3000
CMD ["node", "app.js"]

Create package.json:

JSON
{
  "name": "canary-demo",
  "version": "1.0.0",
  "description": "A simple app for canary deployment demo",
  "main": "app.js",
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "express": "^4.18.2"
  }
}

Now, build and push the v1.0.0 image (replace yourdockerhubuser with your Docker Hub username):

Bash
docker build -t yourdockerhubuser/canary-app:v1.0.0 .
docker push yourdockerhubuser/canary-app:v1.0.0

Next, change the VERSION constant in app.js to 'v1.1.0 - Canary' for the second version.

Build and push the v1.1.0 image:

Bash
docker build -t yourdockerhubuser/canary-app:v1.1.0 .
docker push yourdockerhubuser/canary-app:v1.1.0

2. Deploy the Stable (Baseline) Version

First, we'll deploy our v1.0.0 as the stable baseline application. Create baseline-deployment.yaml:

YAML
# baseline-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: canary-app-baseline
  labels:
    app: canary-app
    track: stable
spec:
  replicas: 3
  selector:
    matchLabels:
      app: canary-app
      track: stable
  template:
    metadata:
      labels:
        app: canary-app
        track: stable
    spec:
      containers:
      - name: app
        image: yourdockerhubuser/canary-app:v1.0.0
        ports:
        - containerPort: 3000
          name: http
        readinessProbe:
          httpGet: { path: /healthz, port: http }
        resources:
          requests:
            cpu: "100m"
            memory: "128Mi"
          limits:
            memory: "128Mi"

The readiness probe matters for canaries: a pod receives traffic only after it passes, so a canary that fails to start never gets requests.

Now, create a Kubernetes Service to expose our application. This service will initially point only to our stable pods but will eventually route traffic to both stable and canary pods based on their replica counts.

Create service.yaml:

YAML
# service.yaml
apiVersion: v1
kind: Service
metadata:
  name: canary-app-service
  labels:
    app: canary-app
spec:
  selector:
    app: canary-app # This selector will match both stable and canary deployments
  ports:
    - protocol: TCP
      port: 80
      targetPort: http
  type: LoadBalancer # Use NodePort for Minikube/local testing or if no LBs are available

Apply these manifests:

Bash
kubectl apply -f baseline-deployment.yaml
kubectl apply -f service.yaml

Verify that v1.0.0 is running. If you're using Minikube, get the service URL:

Bash
minikube service canary-app-service --url
# Or, for external LB, use kubectl get service canary-app-service

Access the URL multiple times; you should consistently see "Hello from v1.0.0 - Baseline!"

3. Introduce the Canary Version

Now, let's deploy our v1.1.0 as the canary. Create canary-deployment.yaml with distinct labels and a smaller replica count (e.g., 1 out of 4 total, or 25% traffic):

YAML
# canary-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: canary-app-canary
  labels:
    app: canary-app
    track: canary # New label to identify canary pods
spec:
  replicas: 1 # Start with a small percentage of traffic
  selector:
    matchLabels:
      app: canary-app
      track: canary
  template:
    metadata:
      labels:
        app: canary-app
        track: canary
    spec:
      containers:
      - name: app
        image: yourdockerhubuser/canary-app:v1.1.0
        ports:
        - containerPort: 3000
          name: http
        readinessProbe:
          httpGet: { path: /healthz, port: http }
        resources:
          requests:
            cpu: "100m"
            memory: "128Mi"
          limits:
            memory: "128Mi"

Apply the canary deployment:

Bash
kubectl apply -f canary-deployment.yaml

Crucially, our canary-app-service has selector: app: canary-app. This selector now matches both canary-app-baseline (pods with app: canary-app, track: stable) and canary-app-canary (pods with app: canary-app, track: canary). The Service sends traffic to every ready pod matching app: canary-app. With 3 baseline replicas and 1 canary replica, the canary gets roughly a quarter of the traffic. That number needs some caveats:

  • The split is per connection, not per request. kube-proxy picks a backend pod when a TCP connection opens. Clients that reuse keep-alive connections (browsers, HTTP/2 clients, other services with connection pools) keep hitting the same pod, so the real share can be far from 25% over short periods.
  • Granularity is limited by replica count. A 5% canary needs at least 20 pods in total. You can't send 1% of traffic to a canary in a 4-pod service.
  • Users can flip between versions. Nothing makes a user stick to one version, so the same person may see v1.0 and v1.1 on consecutive requests. That's a problem if the versions render different UIs or store data differently.

For a first look at a low-risk change, these limits are often acceptable. For precise percentages, header- or cookie-based routing, or sticky sessions, use the tools in the tip below.

Send a batch of requests and count the responses. Use curl without keep-alive so each request opens a new connection:

Bash
for i in $(seq 1 100); do curl -s http://<service-url>/; done | sort | uniq -c

About a quarter of the responses should come from v1.1.0.

4. Monitor and Validate

Compare the canary with the baseline, not with yesterday. Both get the same traffic at the same time, so a difference between them points at the new version. Watch error rate (HTTP 5xx), latency percentiles (p95/p99), restarts, and any business metric the change touches. Decide beforehand how long to watch and which differences trigger a rollback, so the call isn't made on gut feeling. For metrics, this means labelling them by track (or version) so you can chart the two side by side.

Bash
# Check logs for baseline pods
kubectl logs -l app=canary-app,track=stable

# Check logs for canary pods
kubectl logs -l app=canary-app,track=canary

# Restarts and readiness
kubectl get pods -l app=canary-app -L track

💡 Tip: For exact percentages independent of replica counts, split traffic at the routing layer. Gateway API HTTPRoute resources support weighted backendRefs, as do service meshes (Istio, Linkerd) and the NGINX Ingress controller's canary annotations. Argo Rollouts and Flagger go further: they step the weight up automatically, query Prometheus at each step, and roll back on their own if metrics degrade.

5. Promote or Rollback

Based on your monitoring, you'll either promote the canary or roll it back.

Promote the Canary (Full Rollout)

If the canary performs well, you can gradually increase its replicas and decrease the baseline's, or update the baseline deployment to use the new image.

  1. Scale up Canary, scale down Baseline (Gradual Promotion):

    Bash
    kubectl scale deployment canary-app-canary --replicas=3 # e.g., 75% traffic
    kubectl scale deployment canary-app-baseline --replicas=1 # e.g., 25% traffic
    # ... monitor ...
    kubectl scale deployment canary-app-canary --replicas=4 # 100% traffic
    kubectl scale deployment canary-app-baseline --replicas=0

    After scaling up the canary and scaling down the baseline, you might eventually delete the old baseline deployment and rename the canary deployment to canary-app-baseline (or whatever your stable deployment name is). Alternatively, the most common approach is to update the existing baseline deployment with the new image:

  2. Update Baseline Deployment (Standard Promotion): Once confident, update the canary-app-baseline deployment to use v1.1.0 and remove the canary-app-canary deployment:

    Bash
    # Update the baseline deployment to the new image
    kubectl set image deployment/canary-app-baseline app=yourdockerhubuser/canary-app:v1.1.0
    
    # Scale down and delete the temporary canary deployment
    kubectl scale deployment canary-app-canary --replicas=0
    kubectl delete deployment canary-app-canary

Rollback the Canary

If the canary shows issues, you can quickly roll it back:

  1. Scale down the canary deployment to zero replicas:
    Bash
    kubectl scale deployment canary-app-canary --replicas=0
  2. Delete the canary deployment:
    Bash
    kubectl delete deployment canary-app-canary

All traffic will then revert to the v1.0.0 baseline, minimizing impact.

Summary

  1. Two Deployments behind one Service give you a basic canary with no extra tools. The replica ratio sets the approximate traffic share.
  2. Expect a rough split: kube-proxy balances per connection, percentages are limited by replica counts, and users aren't pinned to a version.
  3. Add readiness probes so a broken canary never receives traffic, and label metrics by track to compare canary and baseline directly.
  4. Decide rollback criteria before the rollout, then scale the canary to zero the moment they're hit.
  5. Move to weighted routing (Gateway API, a service mesh) and Argo Rollouts or Flagger when you need precise percentages or automated analysis.
Advertisement