Project 1: CI/CD for a Java Spring Boot App With Jenkins, Docker and Kubernetes

CI CD Pipelines with Jenkins 60 min min read Updated: Nov 17, 2026 Intermediate
Project 1: CI/CD for a Java Spring Boot App With Jenkins, Docker and Kubernetes
Intermediate Topic 1 of 3

What You Will Build

text Git push ─► Jenkins (Multibranch) │ ├─ Checkout ─ Build + unit tests (Maven) ─ JaCoCo coverage ├─ SonarQube analysis ─ Quality Gate (wait) ├─ Docker build ─ Trivy scan ─ Push to registry ├─ Deploy to STAGING with Helm ─ Smoke test └─ Approval ─ Deploy to PRODUCTION with Helm ─ Smoke test ─ (auto rollback on failure)

Requirements

ItemNotes
Jenkins LTS with Java 21Plugins: Pipeline, Git, Credentials Binding, Docker Pipeline, SonarQube Scanner, JUnit, Warnings NG, Slack (optional)
AgentsA Linux agent labelled docker with Docker, JDK 21, Maven wrapper access, kubectl, helm
SonarQube serverToken stored as a Jenkins credential
Container registryDocker Hub, GitHub Container Registry, or a private registry
Kubernetes clusterTwo namespaces: shop-staging and shop-prod (kind, minikube or a cloud cluster)
Credentials in Jenkinsregistry-creds, sonar-token, kubeconfig-staging, kubeconfig-prod

Step 1: The Application

java // src/main/java/com/example/shop/HelloController.java package com.example.shop; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @GetMapping("/api/hello") public String hello() { return "Hello from Shop API"; } }
java // src/test/java/com/example/shop/HelloControllerTest.java package com.example.shop; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class HelloControllerTest { @Test void returnsGreeting() { assertEquals("Hello from Shop API", new HelloController().hello()); } }

Add the Spring Boot actuator dependency so the app exposes /actuator/health for probes and smoke tests, and the JaCoCo and Sonar Maven plugins for coverage and analysis.

Step 2: Dockerfile

docker FROM eclipse-temurin:21-jdk AS build WORKDIR /src COPY .mvn/ .mvn/ COPY mvnw pom.xml ./ RUN ./mvnw -B -q dependency:go-offline COPY src ./src RUN ./mvnw -B -q -DskipTests package FROM eclipse-temurin:21-jre RUN useradd --system --uid 10001 appuser WORKDIR /app COPY --from=build /src/target/*.jar app.jar USER 10001 EXPOSE 8080 HEALTHCHECK --interval=30s --timeout=3s CMD wget -qO- http://localhost:8080/actuator/health || exit 1 ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "/app/app.jar"]
  • Multi-stage build keeps the final image small
  • Runs as a non-root user
  • A .dockerignore file should exclude target/, .git/, and local files

Step 3: Helm Chart (minimal)

yaml # chart/values.yaml image: repository: registry.example.com/team/shop tag: latest replicaCount: 2 service: {port: 80, targetPort: 8080} resources: requests: {cpu: 100m, memory: 256Mi} limits: {memory: 512Mi}
yaml # chart/templates/deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: {{ .Release.Name }} spec: replicas: {{ .Values.replicaCount }} selector: matchLabels: {app: {{ .Release.Name }}} template: metadata: labels: {app: {{ .Release.Name }}} spec: containers: - name: app image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}" ports: [{containerPort: 8080}] readinessProbe: httpGet: {path: /actuator/health/readiness, port: 8080} initialDelaySeconds: 15 livenessProbe: httpGet: {path: /actuator/health/liveness, port: 8080} initialDelaySeconds: 30 resources: {{- toYaml .Values.resources | nindent 12 }} --- apiVersion: v1 kind: Service metadata: name: {{ .Release.Name }} spec: selector: {app: {{ .Release.Name }}} ports: [{port: {{ .Values.service.port }}, targetPort: {{ .Values.service.targetPort }}}]

Step 4: The Jenkinsfile

groovy pipeline { agent none options { timeout(time: 45, unit: 'MINUTES') buildDiscarder(logRotator(numToKeepStr: '20')) disableConcurrentBuilds(abortPrevious: true) timestamps() } environment { REGISTRY = 'registry.example.com' IMAGE = 'team/shop' } stages { stage('Build and test') { agent { label 'docker' } steps { sh './mvnw -B clean verify' } post { always { junit 'target/surefire-reports/*.xml' recordCoverage(tools: [[parser: 'JACOCO']]) } } } stage('Code quality') { agent { label 'docker' } steps { withSonarQubeEnv('sonar-main') { sh './mvnw -B sonar:sonar -Dsonar.projectKey=shop' } timeout(time: 10, unit: 'MINUTES') { waitForQualityGate abortPipeline: true } } } stage('Image') { agent { label 'docker' } steps { script { env.TAG = "${env.BUILD_NUMBER}-${env.GIT_COMMIT.take(7)}" env.FULL_IMAGE = "${REGISTRY}/${IMAGE}:${env.TAG}" } sh 'docker build -t $FULL_IMAGE .' sh 'trivy image --severity HIGH,CRITICAL --exit-code 1 --ignore-unfixed $FULL_IMAGE' withCredentials([usernamePassword(credentialsId: 'registry-creds', usernameVariable: 'U', passwordVariable: 'P')]) { sh 'echo "$P" | docker login $REGISTRY -u "$U" --password-stdin' sh 'docker push $FULL_IMAGE' } } } stage('Deploy staging') { when { branch 'main' } agent { label 'docker' } steps { withCredentials([file(credentialsId: 'kubeconfig-staging', variable: 'KUBECONFIG')]) { sh ''' helm upgrade --install shop chart/ -n shop-staging --create-namespace \ --set image.repository=$REGISTRY/$IMAGE --set image.tag=$TAG \ --atomic --wait --timeout 5m ''' } retry(5) { sleep 5 sh 'curl -fsS https://staging.shop.example.com/actuator/health | grep -q UP' } } } stage('Approve production') { when { branch 'main' } steps { timeout(time: 1, unit: 'DAYS') { input message: "Deploy ${env.TAG} to production?", ok: 'Deploy', submitter: 'release-managers' } } } stage('Deploy production') { when { branch 'main' } agent { label 'docker' } steps { withCredentials([file(credentialsId: 'kubeconfig-prod', variable: 'KUBECONFIG')]) { sh ''' helm upgrade --install shop chart/ -n shop-prod --create-namespace \ --set image.repository=$REGISTRY/$IMAGE --set image.tag=$TAG \ --atomic --wait --timeout 5m ''' } sh 'curl -fsS https://shop.example.com/actuator/health | grep -q UP' } } } post { failure { slackSend channel: '#builds', color: 'danger', message: "FAILED ${env.JOB_NAME} #${env.BUILD_NUMBER} ${env.BUILD_URL}" } fixed { slackSend channel: '#builds', color: 'good', message: "FIXED ${env.JOB_NAME} #${env.BUILD_NUMBER}" } } }

Step 5: Create the Job and Run It

  1. Push the code, Dockerfile, chart/ and Jenkinsfile to Git
  2. In Jenkins create a Multibranch Pipeline, add the repository and credentials
  3. Add a webhook so pushes start builds
  4. Open a feature branch and a pull request: build, test, scan and image stages run, deploy stages are skipped
  5. Merge to main: staging deploys automatically, then waits for approval
  6. Approve and watch production roll out

Step 6: Break Things on Purpose

ExperimentExpected result
Make a unit test failBuild stops at test stage, JUnit report shows the failure
Add a code smell that lowers qualityQuality gate fails; pipeline aborts
Use an old base image with known CVEsTrivy stage fails the build
Deploy an image with a bad readiness probe--atomic rolls back; production keeps the old version
Click Abort at the approvalProduction is untouched

Extra Challenges

  • Add a parallel stage for unit tests and a linter
  • Cache Maven dependencies on the agent or with BuildKit cache
  • Add cosign signing and an SBOM artifact
  • Create a rollback job that takes a tag as a parameter
  • Switch the deploy stages to GitOps: Jenkins commits the tag to a config repo and Argo CD syncs

Self-Check

  1. Can a developer see the result of a pull request build without any production access?
  2. Is production deployed only from main and only after approval?
  3. Does every image have a unique, traceable tag?
  4. Does a failed deploy roll back by itself?
  5. Can you recreate this pipeline on a new Jenkins from Git alone?

Conclusion

You built an end-to-end pipeline: Maven build and tests, coverage, SonarQube quality gate, Docker build, Trivy scan, registry push, Helm deployment to staging with a smoke test, manual approval, and an atomic production release. Pull requests run checks only; main deploys.

Quick Summary: app + test; multi-stage Dockerfile; Helm chart; full Jenkinsfile (sonar gate, trivy, helm --atomic, approval); multibranch setup; failure experiments.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators