Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 40 ยท Deployment and Delivery

Deploying to Kubernetes from a Jenkins pipeline

Build an image, push it and roll it out to Kubernetes from a Jenkinsfile with kubectl or Helm: credentials, rolling updates, smoke checks, rollback and a runnable rollout simulator.

You can build and test code in a pipeline, and you can build a Docker image (see Docker Agents and Building Images). The last step is to make the new image run somewhere. Many teams run their applications on Kubernetes, a platform that keeps a desired number of copies of your container running, replaces them gradually during updates and restarts them when they fail. This lesson shows the shape of a Jenkins pipeline that deploys a Java or Python application to Kubernetes, and the checks that make such a deployment safe.

Kubernetes itself is a large topic; here you need only a few ideas. A real cluster, Docker and Jenkins cannot run on this site, so the pipeline and manifests are read-only and the runnable example is a stand-in simulator of a rolling update, written in JavaScript. For commands such as kubectl and helm, check your cluster's version and documentation.

The minimum Kubernetes you need

  • A Pod is the smallest unit: one or more containers running together.
  • A Deployment describes the desired state: "run 3 copies of image shop:1.4.2". Kubernetes creates ReplicaSets and pods to match it and replaces pods one by one when you change the image.
  • A Service gives the pods a stable name and load-balances traffic to them.
  • A namespace separates environments or teams inside one cluster, such as staging and production.
  • Probes let Kubernetes ask the app whether it is alive (liveness) and ready to receive traffic (readiness).

A small Deployment and Service, read-only:

YAML
apiVersion: apps/v1
kind: Deployment
metadata:
  name: shop
  namespace: staging
spec:
  replicas: 3
  selector:
    matchLabels: { app: shop }
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxUnavailable: 1
      maxSurge: 1
  template:
    metadata:
      labels: { app: shop }
    spec:
      containers:
        - name: shop
          image: registry.example.com/shop:1.4.2
          ports:
            - containerPort: 8080
          readinessProbe:
            httpGet: { path: /health, port: 8080 }
            initialDelaySeconds: 5
          resources:
            requests: { cpu: 100m, memory: 256Mi }
            limits:   { memory: 512Mi }
---
apiVersion: v1
kind: Service
metadata:
  name: shop
  namespace: staging
spec:
  selector: { app: shop }
  ports:
    - port: 80
      targetPort: 8080

The pipeline

The pipeline does the same things regardless of language: build and test, make an image with a unique tag, push it, update the Deployment, wait for the rollout and verify. Only the build commands differ: mvn -B verify for a Java project, pytest for a Python one.

GROOVY
pipeline {
  agent { label 'docker' }
  environment {
    REGISTRY = 'registry.example.com'
    IMAGE    = "${REGISTRY}/shop"
    TAG      = "${env.GIT_COMMIT.take(8)}"
  }
  stages {
    stage('Test') {
      steps { sh 'mvn -B verify' }                    // Python: sh 'pytest -q'
      post { always { junit 'target/surefire-reports/*.xml' } }
    }
    stage('Build image') {
      steps { sh 'docker build -t "$IMAGE:$TAG" .' }
    }
    stage('Push image') {
      steps {
        withCredentials([usernamePassword(credentialsId: 'registry', usernameVariable: 'U', passwordVariable: 'P')]) {
          sh 'echo "$P" | docker login "$REGISTRY" -u "$U" --password-stdin'
          sh 'docker push "$IMAGE:$TAG"'
        }
      }
    }
    stage('Deploy to staging') {
      steps {
        withCredentials([file(credentialsId: 'kubeconfig-staging', variable: 'KUBECONFIG')]) {
          sh 'kubectl -n staging set image deployment/shop shop="$IMAGE:$TAG"'
          sh 'kubectl -n staging rollout status deployment/shop --timeout=180s'
        }
      }
    }
    stage('Smoke test') {
      steps { sh './ci/smoke.sh https://staging.shop.example.com' }
    }
    stage('Approve production') {
      when { branch 'main' }
      steps { input message: 'Deploy this version to production?', ok: 'Deploy' }
    }
    stage('Deploy to production') {
      when { branch 'main' }
      steps {
        withCredentials([file(credentialsId: 'kubeconfig-prod', variable: 'KUBECONFIG')]) {
          sh 'kubectl -n production set image deployment/shop shop="$IMAGE:$TAG"'
          sh 'kubectl -n production rollout status deployment/shop --timeout=300s'
        }
      }
    }
  }
  post {
    failure {
      echo 'If production was touched, roll back with: kubectl -n production rollout undo deployment/shop'
    }
  }
}

Points to notice:

  • Unique tags. The image tag is the commit id, never latest. Kubernetes only rolls out when the image string changes, and a unique tag also tells you exactly which code is running.
  • Credentials, not secrets in code. The registry login and the kubeconfig come from Jenkins credentials (see Credentials and Secrets). Give each environment its own kubeconfig and an account with minimal rights, for example one namespace only.
  • rollout status waits until the new pods are ready and returns a non-zero exit code if the rollout does not complete in time, which fails the stage. Without it, the pipeline would report success while the pods crash.
  • Approval before production uses input (see Deployment Pipelines and Approvals).
  • Rollback. kubectl rollout undo returns to the previous ReplicaSet. Because every image has a unique tag, you can also redeploy any older tag.

With Helm

Many teams package manifests as a Helm chart and let one command install or upgrade the release with the new image:

Terminal
helm upgrade --install shop ./chart \
  --namespace staging --create-namespace \
  --set image.repository="$IMAGE" --set image.tag="$TAG" \
  --atomic --timeout 5m

--atomic rolls the release back automatically if the upgrade fails, and helm rollback shop returns to an earlier revision.

Jenkins running on Kubernetes

The relationship also works the other way. With the Kubernetes plugin, Jenkins creates a temporary agent pod for each build and deletes it afterwards, which scales builds without permanent machines (see Agents, Labels and Scaling). The pipeline then uses a kubernetes { yaml '...' } agent block to list the containers it needs, such as maven, kubectl and docker.

Rollout strategies

How the new version replaces the old one matters for users:

  • Rolling update (the Kubernetes default): replace pods gradually; during the update both versions exist. Needs backward-compatible changes (a database schema change must work for the old and the new code).
  • Recreate: stop all old pods, then start new ones. Simple, but there is downtime.
  • Blue-green: run the new version next to the old, switch traffic at once, keep the old one for fast rollback. Costs double the resources briefly.
  • Canary: send a small share of traffic to the new version, watch metrics, then increase.

Rolling update is enough for most applications; blue-green and canary usually need extra tooling or a service mesh (see Jenkins vs TeamCity, Bamboo, Travis CI, Spinnaker, Maven and Kubernetes).

Simulating a rolling update

The stand-in below models a Deployment with 4 replicas, maxSurge 1 and maxUnavailable 1. It starts new pods, waits for readiness, and removes old pods. It also shows what happens when the new version's readiness probe never passes: the rollout stalls and the old pods keep serving traffic, which is exactly why rollout status times out and fails the pipeline.

JS A rolling update, step by step

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The simulation is a simplified model. Real Kubernetes works in terms of ReplicaSets, uses maxSurge and maxUnavailable as numbers or percentages and waits for minReadySeconds, but the key behavior is accurate: readiness gates traffic, so a broken version does not take the service down.

Checks before and after

Add these to the pipeline stages:

  1. Lint the manifests (kubectl apply --dry-run=server -f k8s/ or helm lint) before the deploy.
  2. Wait for rollout with a timeout.
  3. Smoke test the public URL (/health, one real request).
  4. Record the deployed tag, for example in the build description and a Git tag.
  5. Alert on failure with a notification (see Administration recipes for Slack).
JS A smoke test decision

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should the pipeline tag images with the commit id instead of latest?

    An unchanged image string triggers no rollout, and unique tags make versions traceable and easy to roll back to.
  2. 2. What does kubectl rollout status do in the pipeline?

    It turns a stuck rollout into a failed stage, instead of a false success.
  3. 3. A new version fails its readiness probe during a rolling update. What happens to users?

    Only ready pods receive traffic, so the stalled rollout leaves the old version serving.
  4. 4. Which rollout strategy sends a small share of traffic to the new version first?

    A canary release exposes the new version to a small portion of traffic and expands it if metrics look healthy.

Summary

  • Kubernetes runs the containers; Jenkins builds, pushes and updates the Deployment with kubectl set image or Helm.
  • Tag images uniquely, keep per-environment kubeconfigs in Jenkins credentials, and wait with rollout status.
  • Probes make rolling updates safe: unready pods never receive traffic, so a bad version stalls instead of causing an outage.
  • Add smoke tests, an approval before production and a rollback path (rollout undo, helm rollback or redeploying an old tag).
  • Choose a rollout strategy (rolling, recreate, blue-green, canary) for your tolerance for risk and downtime.

Next: Project: CI for a Java Application.