Kubernetes Spring Boot

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

The Project’s Structure:

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:

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:

The resources can be visualized as follows:

Inside the Cluster

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.

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