Table of Contents
Deploying a Spring Boot application on Kubernetes can seem daunting for beginners, but with a clear step-by-step approach, it becomes manageable and rewarding. This tutorial guides you through the entire process, from containerizing your Spring Boot app to deploying it on a Kubernetes cluster.
Prerequisites
- Java Development Kit (JDK) installed
- Spring Boot application ready
- Docker installed and configured
- Kubernetes cluster (local like Minikube or cloud-based)
- kubectl command-line tool installed
Step 1: Containerize Your Spring Boot Application
Create a Dockerfile in your project directory with the following content:
Dockerfile
FROM openjdk:17-jdk-slim
VOLUME /tmp
EXPOSE 8080
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar","/app.jar"]
Build the Docker image:
docker build -t springboot-k8s:latest .
Step 2: Push Docker Image to Registry
If using Docker Hub, log in and push your image:
docker login
docker tag springboot-k8s:latest yourdockerhubusername/springboot-k8s:latest
docker push yourdockerhubusername/springboot-k8s:latest
Step 3: Create Kubernetes Deployment
Write a deployment YAML file (deployment.yaml):
deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: springboot-deployment
spec:
replicas: 3
selector:
matchLabels:
app: springboot
template:
metadata:
labels:
app: springboot
spec:
containers:
- name: springboot
image: yourdockerhubusername/springboot-k8s:latest
ports:
- containerPort: 8080
Step 4: Expose Your Deployment
Create a service YAML file (service.yaml):
service.yaml
apiVersion: v1
kind: Service
metadata:
name: springboot-service
spec:
type: LoadBalancer
selector:
app: springboot
ports:
- protocol: TCP
port: 80
targetPort: 8080
Step 5: Deploy to Kubernetes
Apply the deployment and service files:
kubectl apply -f deployment.yaml
kubectl apply -f service.yaml
Step 6: Access Your Application
If using Minikube, run:
minikube service springboot-service
For cloud clusters, find the external IP address assigned to your service:
kubectl get svc springboot-service
Conclusion
Deploying a Spring Boot application on Kubernetes involves containerization, creating deployment and service configurations, and applying them to your cluster. With these steps, you can efficiently manage and scale your Java applications in a cloud environment or local setup.