Spring Boot Application K3s Deployment and Jenkins CI/CD: Integration Guide

Spring Boot Application K3s Deployment and Jenkins CI/CD: Integration Guide
Photo by Growtika / Unsplash

In today's cloud-native era, deploying applications to Kubernetes and implementing continuous integration and continuous deployment (CI/CD) has become best practice. This guide will help you deploy a Spring Boot application to the lightweight Kubernetes distribution K3s, and create a complete CI/CD process using Jenkins for automated deployment.

Table of Contents

  1. Prerequisites
  2. Environment Preparation
  3. Configuring Jenkins
  4. Creating Dockerfile and Kubernetes Deployment Files
  5. Setting Up Jenkins Pipeline
  6. Configuring GitHub Webhook
  7. Running and Testing CI/CD Process
  8. Verifying and Accessing the Application
  9. Conclusion

Prerequisites

Before starting, ensure that you have:

  1. Installed Docker
  2. Installed K3s
  3. Prepared a Spring Boot application
  4. Installed the kubectl command-line tool
  5. Installed Jenkins
  6. A GitHub account and repository

Environment Preparation

Get the K3s kubeconfig file:

sudo cat /etc/rancher/k3s/k3s.yaml

Save this file; we'll use it in Jenkins later.

Ensure K3s is running:

sudo systemctl status k3s

Configuring Jenkins

  1. Install necessary Jenkins plugins:
    • Docker Pipeline
    • Kubernetes CLI
    • GitHub Integration
  2. Configure the following credentials in Jenkins:
    • GitHub credentials (for accessing your code repository)
    • Docker Hub credentials (for pushing Docker images)
    • Kubernetes configuration file (using the content of the k3s.yaml file saved earlier)

Creating Dockerfile and Kubernetes Deployment Files

Create a deployment.yaml file:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: myspringapp
spec:
  replicas: 1
  selector:
    matchLabels:
      app: myspringapp
  template:
    metadata:
      labels:
        app: myspringapp
    spec:
      containers:
      - name: myspringapp
        image: yourdockerhubusername/myspringapp:${BUILD_NUMBER}
        ports:
        - containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
  name: myspringapp-service
spec:
  selector:
    app: myspringapp
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080
  type: LoadBalancer

Create a Dockerfile in the root directory of your Spring Boot project:

FROM openjdk:11-jre-slim
VOLUME /tmp
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar","/app.jar"]

Setting Up Jenkins Pipeline

  1. Create a new pipeline project in Jenkins.
  2. Create a Jenkinsfile in your GitHub repository:
pipeline {
    agent any
    
    environment {
        DOCKER_IMAGE = "yourdockerhubusername/myspringapp"
        DOCKER_TAG = "${env.BUILD_NUMBER}"
    }
    
    stages {
        stage('Checkout') {
            steps {
                checkout scm
            }
        }
        
        stage('Build') {
            steps {
                sh 'mvn clean package'
            }
        }
        
        stage('Docker Build') {
            steps {
                script {
                    docker.build("${DOCKER_IMAGE}:${DOCKER_TAG}")
                }
            }
        }
        
        stage('Docker Push') {
            steps {
                script {
                    docker.withRegistry('', 'docker-hub-credentials') {
                        docker.image("${DOCKER_IMAGE}:${DOCKER_TAG}").push()
                        docker.image("${DOCKER_IMAGE}:${DOCKER_TAG}").push("latest")
                    }
                }
            }
        }
        
        stage('Deploy to K3s') {
            steps {
                script {
                    withKubeConfig([credentialsId: 'k3s-config']) {
                        sh "sed -i 's|${DOCKER_IMAGE}:.*|${DOCKER_IMAGE}:${DOCKER_TAG}|' deployment.yaml"
                        sh "kubectl apply -f deployment.yaml"
                        sh "kubectl rollout status deployment/myspringapp"
                    }
                }
            }
        }
    }
    
    post {
        always {
            cleanWs()
        }
    }
}
  1. In the Jenkins project configuration, set "Pipeline script from SCM" and point to your GitHub repository.

Configuring GitHub Webhook

  1. Add a Webhook in your GitHub repository settings.
  2. Set the Webhook URL to http://your-jenkins-url/github-webhook/.
  3. Choose "Just the push event" as the trigger event.

Running and Testing CI/CD Process

  1. Make changes to your Spring Boot application.
  2. Commit and push the changes to GitHub.
  3. Observe Jenkins automatically triggering the build process.
    • Jenkins will check out the code
    • Build the Spring Boot application
    • Create a Docker image
    • Push the image to Docker Hub
    • Update the deployment in K3s

Verifying and Accessing the Application

  1. Access the application:
    • Access http://localhost:8080 in your browser
    • Access the application using the assigned external IP

If running K3s on a remote server, get the external IP of the service:

kubectl get service myspringapp-service

If running K3s locally, use port forwarding:

kubectl port-forward service/myspringapp-service 8080:80

Verify the deployment status using kubectl:

kubectl get deployments
kubectl get pods
kubectl get services

Conclusion

Through this integration guide, we have successfully deployed a Spring Boot application to a K3s cluster and established a complete CI/CD process using Jenkins. This automated approach not only improves development efficiency but also ensures consistency and reliability in the deployment process.

Key points:

  1. Use Dockerfile to define the application container
  2. Use Kubernetes deployment file to describe the desired application state
  3. Jenkins pipeline automates the entire process from code change to deployment
  4. GitHub Webhook enables automatic triggering after code push

As you deepen your understanding of this process, you can further optimize the CI/CD pipeline, such as adding automated testing, environment-specific configurations, monitoring, and log collection.

I hope this comprehensive guide helps you successfully deploy Spring Boot applications on K3s and establish a robust CI/CD process. Best wishes for your cloud-native journey!