Kubernetes Spring Boot

Let’s build the simplest Java Spring Boot application that runs as a pod in a Kubernetes cluster

Kajal Rawal
2 min readNov 2, 2020

The Project’s Structure:

├── Dockerfile
├── build.gradle
├── gradle
│ └── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── k8s
│ └── depl.yaml
├── settings.gradle
└── src
└── main
└── java
└── hello
├── App.java
└── HelloWorldCtrl.java

Our App.java is the entry point of the application:

The code above contains the minimal lines needed to create a Spring Boot application.

The HelloWorldCtrl.java contains a simple controller that maps the root path (“/”) and returns a greeting String:

Creating K8s Resources

In order to create a K8s deployment, we’ll need a Docker image. Let’s add the following lines to our Dockerfile:

The steps in our Docker file:

  • Copy the project to /app
  • Build the project using Gradle
  • Run the application using the result of the previous step

We can now build the image and push to the hub:

docker build -t kajalrawal/hello-spring .
docker push kajalrawal/hello-spring

The K8s deployment is simple. It consists of a deployment and a service:

The deployment defines two replicas of the pod that will be running the container that’s built from the image specified in the image attribute.

The service is of type ClusterIP (the default Kubernetes service). It gives us a service inside our cluster that other apps can access.

Creating the resources in your cluster:

kubectl create -f <yaml_file>

The resources can be visualized as follows:

+---------------------+
| hello-world-service |
| |
| 10.15.242.210 |
+---------O-----------+
|
+-------------O--------------------------O
| |
+---------O-----------+ +---------O-----------+
| pod 1 | | pod 2 |
| | | |
| hello-world | | hello-world |
+---------------------+ +---------------------+

Inside the Cluster

$ kubectl get pods
NAME READY STATUS RESTARTS AGE
hello-world-5bb87c95-6h4kh 1/1 Running 0 7h
hello-world-5bb87c95-bz64v 1/1 Running 0 7h
$ kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
hello-world-service ClusterIP 10.15.242.210 <none> 8080/TCP 5s
kubernetes ClusterIP 10.15.240.1 <none> 443/TCP 7h
$ kubectl exec -it hello-world-5bb87c95-6h4kh bash
$ (inside the pod) curl 10.15.242.210:8080
$ (inside the pod) Greetings from Spring Boot!

We can see that the server is up and is running inside the pods. Depending on your cloud provider, you can set a service of type LoadBalancer and access the application from outside the cluster.

Conclusion

We created a simple Spring Boot application, wrapped it in a Docker container, and used the container in a K8s pod, which was orchestrated by a K8s deployment and exposed through a service.

The service provides a simple load balancer to the two created pods and can be easily scaled according to the application needs.

--

--

Kajal Rawal

Programming isn’t about what you know; it’s about what you can figure out.