7/20/2021

Simple SpringBoot Application Deployment In Kubernetes

 



The purpose of this blog post is to explain how to deploy simple spring boot application inside Kubernetes cluster and access rest services which exposed by those applications.


Please note this is not my own creation but inspired by another blog post.

Also I am using minikube as single node Kubernetes cluster and you can follow below official document to learn more about it.

https://minikube.sigs.k8s.io/docs/


Steps to follow


  • Start minikube

$ minikube start


  • Open minikube tunnel  in another terminal to enable access k8s services out side the cluster


$ minikube tunnel



  • Clone SpringBoot repository




cd ./tutorials/spring-cloud/spring-cloud-kubernetes/kubernetes-minikube



  • Building demo-backend  app & Docker image




cd ./demo-backend


mvn package spring-boot:repackage

# this is important otherwise k8s cluster can't pull the docker image

eval $(minikube docker-env)

docker build --file=Dockerfile   --tag=demo-backend:latest --rm=true .



  • Building demo-frontend  app & Docker image


/kubernetes-minikube/demo-frontend$ mvn package spring-boot:repackage

docker build --file=Dockerfile   --tag=demo-frontend:latest --rm=true .




  • Deploy backend and frontend applications



kubectl create deploy demo-backend --image=demo-backend:latest --port=8080 --replicas=3  --dry-run=client -o yaml > deploy.yml


vi deploy.yml



We need to change the image pull policy to Never in deployment (line: 22). Please refer below document for more details.






kubectl apply -f deploy.yml 




kubectl create deploy demo-frontend --image=demo-frontend:latest --port=8081 --replicas=3  --dry-run=client -o yaml > frontend.yml



Edit image pull policy as below and deploy

kubectl apply -f frontend.yml



  • Expose both frontend and backend deployments/apps 




dhanuka@dhanuka:~/kubernetes-minikube$ kubectl expose deploy demo-backend 

service/demo-backend exposed


dhanuka@dhanuka:~/kubernetes-minikube$ kubectl expose deploy demo-frontend --type=NodePort

service/demo-frontend exposed #Get the node_ip and node_port for external access for front-end service

dhanuka@dhanuka:~/kubernetes-minikube$ minikube service --url  demo-frontend

http://192.168.49.2:32143






  • Access the backend through frontend




Explaining with SpringBoot application.

Backend application expose a rest API with server port 8080 and return a message with "Hello from " prefix and pod name.






Frontend application expose an rest API with server port 8081 and return a message with "Message from backend is: " prefix plus message getting from Backend service.







So when we access the front end service with node_ip and node_port as below we will get the message as below.

http://192.168.49.2:32143

Message from backend is: Hello from demo-backend-fc9f8c8b9-tcqtz



No comments:

Post a Comment