Monday, 12 May 2025

Step-by-Step: Deploy Spring Boot on Kubernetes

 1. Build the Spring Boot App

a)Make sure your app is working locally, then build or run it using Maven or Gradle:

./mvnw clean package

b)If you want to skip tests while building

./mvnw clean package -DskipTests

This creates a target/<my-spring-boot-app-0.0.1-SNAPSHOT>.jar file.

(Replace my-spring-boot-app with your actual artifact ID)


c)Then run the JAR Locally

java -jar target/my-spring-boot-app-0.0.1-SNAPSHOT.jar

d) 📁 Example Directory After Build:
my-spring-boot-app/
├── src/
├── target/
│   ├── classes/
│   ├── my-spring-boot-app-0.0.1-SNAPSHOT.jar
│   └── ...
├── pom.xml
├── mvnw
├── mvnw.cmd
└── ...



2. Create a Dockerfile
In your project root, create a file named Dockerfile:

FROM openjdk:17
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java", "-jar", "/app.jar"]

3. Build and Push the Docker Image
docker build -t your-dockerhub-username/springboot-app:latest

Push it to Docker Hub (or any container registry):

docker push your-dockerhub-username/springboot-app:latest

Note: Replace your-dockerhub-username accordingly.

4. Create Kubernetes Deployment YAML
Create a file named deployment.yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: springboot-deployment
spec:
  replicas: 2
  selector:
    matchLabels:
      app: springboot-app
  template:
    metadata:
      labels:
        app: springboot-app
    spec:
      containers:
      - name: springboot-container
        image: your-dockerhub-username/springboot-app:latest
        ports:
        - containerPort: 8080

5. Create Kubernetes Service YAML
Create a file named service.yaml:

apiVersion: v1
kind: Service
metadata:
  name: springboot-service
spec:
  selector:
    app: springboot-app
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080
  type: LoadBalancer  # Use NodePort if not using a cloud provider

6. Deploy to Kubernetes
Apply the configuration:

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

7. Verify
kubectl get pods
kubectl get deployments
kubectl get services

Look for the EXTERNAL-IP of your service (may take a minute to appear if using LoadBalancer on cloud).

8. Access the App
Open the EXTERNAL-IP in your browser. If using NodePort, access it with:

http://<Node-IP>:<NodePort>

Tips:
Use ConfigMap or Secrets for environment variables
For production, consider using Helm, Ingress, TLS, and Horizontal Pod Autoscaler.
For local Kubernetes: use Minikube, Docker Desktop, or Kind.
--------------------------------------


No comments:

Post a Comment