Deploy Spring Boot microservices on kubernetes?

TL;DR: This is going to be long post and the objective of this blog post is to deploy Spring Boot Microservice into the kubernetes cluster.

The main objective here is to build everything from scratch and what I mean by that - creating a Spring Boot Application RestMicroservice, Building a Docker image and Finally deploying docker image into the kubernetes cluster. Here are the steps which we will go through -

Kubernetes Part -1 : Steps to Deploy Spring Boot application in Kubernetes running on Virtual Machine

  1. Create a Spring Boot Application using the Spring Boot Initializr
  2. Import the spring boot project into IDE
  3. Implement your microservice
  4. Test the rest webservice
  5. Create Dockerfile for spring boot application
  6. Create Docker registry at "https://hub.docker.com/"
  7. "docker build" && "docker push image"
  8. Start kubernetes cluster
  9. Deploy Spring Boot microservices on kubernetes
  10. Clean up the Deployment and Service


Kubernetes Part -2 : Steps to Deploy Spring Boot application in Kubernetes running on Google Cloud

  1. Create a project on Google Cloud
  2. Create Kubernetes Cluster on Google Cloud
  3. Push spring boot docker image to google container registry(gcr.io)
  4. Deploy the spring boot microservice inside kubernetes cluster running on Google Cloud

In the Part-1 of this blog we will first build and deploy Spring Boot microservice application into the Kubernetes cluster running into virtual machine using Vagrant and in the Part-2 of this blog we will use Google Cloud to deploy the same Spring Boot microservice application.

Here are some more advance topics-

If you are interested in taking the same application to Jenkins CI/CD

  1. Setting up CI/CD Jenkins pipeline for kubernetes using Spring Boot Application on Virtual machine
  2. Setting up kubernetes jenkins pipeline on AWS using Spring boot Application

Part 1 - Deploy spring boot microservice on local kubernetes cluster using Kubespray

As we know our final goal is to "deploy spring boot micro-services on kubernetes" but before that, we need to build our spring boot application.



1. Create a Spring Boot Application using the Spring Boot Initializr

Let's head over to spring initializr(https://start.spring.io/) for generating skeleton for our spring boot application.(Note: This complete setup has been tested with Spring Boot Version v2.5.4)

Fill in the following details for spring boot application -

  • Group - com.jhooq
  • Artifacts - Jhooq-k8s
  • Project - Gradle Project
  • Packaging - Jar
  • Java - 11

Deploy Spring Boot microservices on kubernetes

Now click on the "Add Dependecies" sections to add "Spring Web" dependencies which include RESTful, application using Spring MVC and uses Apache Tomcat as the default embedded cotainer.

Spring initalizr for building spring boot application

After you ready to go and click on "Generate CTRL+↵" and save the zip file containing spring boot skeleton project.



2. Import the spring boot project into IDE

The next step would be to extract the zip file which you have downloaded in the - Step 1

Open you favorite IDE to import the project.(In my case i am using Intellij Idea). It should look something like this

Intellij import spring boot project



3. Implement your microservice

For the simplicity we will be implementing a very simple "Hello World" microservice and accessing it with either web browser or curl from the terminal.

Here is my RestController class called JhooqController

 1package com.jhooq.Jhooqk8s.ws;
 2
 3import org.springframework.web.bind.annotation.GetMapping;
 4import org.springframework.web.bind.annotation.RestController;
 5
 6@RestController
 7public class JhooqController {
 8
 9    @GetMapping("/hello")
10    public String hello() {
11        return "Hello - Jhooq-k8s";
12    }
13}

Next step would be to build your Spring boot project using gradle

Run the following gradle build command -

1$ ./gradlew build
2
3> Task :test
42020-05-16 13:03:51.176  INFO 6235 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'
5
6BUILD SUCCESSFUL in 6s
75 actionable tasks: 5 executed

Now you have build your Spring Boot project and its time to run the Spring boot application.

Switch to the "build/libs" directory and you should see your jar file over there .i.e. - Jhooq-k8s-0.0.1-SNAPSHOT.jar

1$ cd build/libs/
1$ ls -lart
2total 17228
3drwxrwxr-x 2 rahul rahul     4096 touko  16 13:03 .
4-rw-rw-r-- 1 rahul rahul 17633090 touko  16 13:03 Jhooq-k8s-0.0.1-SNAPSHOT.jar
5drwxrwxr-x 9 rahul rahul     4096 touko  16 13:03 ..

Now run the spring boot application

1$ java -jar Jhooq-k8s-0.0.1-SNAPSHOT.jar

You should following successful start message

1Started JhooqK8sApplication in 2.099 seconds (JVM running for 2.517)


4. Test the rest webserive

Once your spring boot application has started, now you can test the rest end point

1$ curl http://localhost:8080/hello
1Hello - Jhooq-k8s

5. Create Dockerfile for spring boot application

After testing your spring boot rest endpoint, now you need to create docker container of your Spring boot application.

To do that you need create the Dockerfile. You can create Dockerfile at any location. In this example we have created the Dockerfile at root level.

Docker file location in Spring boot project

Now you need write some docker command for creating Docker container

1FROM openjdk:8-jdk-alpine
2ARG JAR_FILE=build/libs/*.jar
3COPY ${JAR_FILE} app.jar
4ENTRYPOINT ["java","-jar","/app.jar"]

(Note - You need to be careful about the path to pick the Jhooq-k8s-0.0.1-SNAPSHOT.jar file. In this example our jar file location is build/libs/, So the docker file command should be **_ARG JAR_FILE=build/libs/.jar** )

6. Create Docker registry at "https://hub.docker.com/"

Before we build our docker image, the first thing we need to do is create a docker registry at "https://hub.docker.com/". So that we will push our spring boot docker image into the registry. Later on, we will pull the same docker image during kubernetes deployment.

Goto "https://hub.docker.com/" and click on "Create Repository"

Docker hub create registry for spring boot container

Now it will prompt you for the docker registry name, in this example I am going to put my registry name as - jhooq-k8s-springboot.

Based on your privacy settings either you can keep the docker registry either Public or Private.

Docker hub create registry for spring boot container

Once you click on the save button you can see verify your docker registry onto the dashboard of your "https://hub.docker.com/"

Created docker hub repository for spring boot kubernetes deployment

7. "docker build" && "docker push image"

Now you have all the per-requisites done for building docker image and pushing it to the "https://hub.docker.com/".

But the first thing - Let's build our docker image and assign a suitable tag name to the docker image

Step 1 - Build docker image and tag it with the name "jhooq-k8s-springboot"

1$ docker build -t jhooq-k8s-springboot .

Step 2 - Since our registry name on dockerhub is "rahulwagh17/jhooq-k8s-springboot" so we need to tag the build image one more time with docker registry name

1$ docker tag jhooq-k8s-springboot rahulwagh17/kubernetes:jhooq-k8s-springboot

Step 3 - Push the docker image to docker hub

1$ docker push  rahulwagh17/kubernetes:jhooq-k8s-springboot
1The push refers to repository [docker.io/rahulwagh17/kubernetes]
214170fe294f1: Pushed 
3ceaf9e1ebef5: Layer already exists 
49b9b7f3d56a0: Layer already exists 
5f1b5933fe4b5: Layer already exists 
6jhooq-k8s-springboot: digest: sha256:b50ccfc5f80308795051b75fe69cc76f30dc37996b2c6065d2c978125621aefa size: 1159

Great now our spring boot docker image is onto the docker hub. Let's move onto our next step where we will be starting our kubernetes cluster to deploy "docker container" which we just pushed onto docker hub.

8. Start kubernetes cluster

If you do not have kubernetes cluster running than please stop here and I would highly recommend going through the guide on - Kubespray – 12 Steps for Installing a Production Ready Kubernetes Cluster.

(Note: - I have tested the kubernetes cluster setup with latest available version of kubernetes v1.22)

Alright so if you have reached so far then you have pretty much set up your kubernetes cluster to deploy spring boot application on kubernetes.

If you havn't run the kuberspray ansible then you could re-run it.

1vagrant@amaster:~/kubespray$ ansible-playbook -i inventory/mycluster/hosts.yml --become --become-user=root cluster.yml

The ansible playbook will take some time to finish, once your ansible playbook run has finished successful then you should login to your kubernetes master node

1$vagrant ssh kmaster

9. Deploy Spring Boot microservices on kubernetes

Now you have logged into your kubernetes master node, we need to create deployment using kubectl.

Step 1 - Use the following command to create kubectl deployment with the name demo

1vagrant@kmaster:~$ kubectl create deployment demo --image=rahulwagh17/kubernetes:jhooq-k8s-springboot

Check the deployment using following command

1$ kubectl get deployments
2NAME   READY   UP-TO-DATE   AVAILABLE   AGE
3demo   1/1     1            1           5h20m

Step 2 - Expose the deployment to outside world

1vagrant@kmaster:~$ kubectl expose deployment demo --type=LoadBalancer --name=demo-service --external-ip=1.1.1.1 --port=8080
1service/demo-service exposed

Step 3 - Check the services

After exposing the service verify it with the following command

1$ kubectl get service

It should return something similar

1NAME           TYPE           CLUSTER-IP     EXTERNAL-IP   PORT(S)          AGE
2demo-service   LoadBalancer   10.233.5.144   1.1.1.1       8080:31901/TCP   2s
3kubernetes     ClusterIP      10.233.0.1     <none>        443/TCP          28h

Step 4 - Curl or test the rest endpoint

Since we setup the kubernetes cluster on laptop, so to access the spring boot rest point outside of the cluster we need to use vagrant box(kmaster's) ip address .i.e. - 100.0.0.2

So from your laptop which is outside the cluster you can use the following curl command

1$ curl http://100.0.0.2:31901/hello
1Hello - Jhooq-k8s

And if you are interested in accessing it from browser then please refer to the following screenshot

kubernetes expose service external ip

But in case if you have deployed the cluster on AWS(Amazon web service) or Google Cloud then use the EXTERNAL-IP which you got after running the command $ kubectl get service .i.e.

1$ curl http://1.1.1.1:31901/hello

Great you have deployed your Spring Boot microservices on kubernetes.

10. Clean up the Deployment and Service

Once you are done with the deployment and exposing the deployment as a service. You can run the following command to clean the kubernetes cluster

1$ kubectl delete service demo-service
1$ kubectl delete deplopyments demo

Part 2 - Deploy spring boot microservice on Google Cloud Platform (GCP)

In the Part-1 we setup local kubernetes cluster using kubespray and then deployed spring boot application on it.

Now in the Part-2 we are going to deploy the same Spring boot application on Google Cloud Platform (GCP)

Prerequisite

1. Create a project on Google Cloud

After the login goto "My First Project" and click on it.

Google cloud goto my first project

Now we need to click on the New Project to create a new project

Google cloud goto new project

Enter the name of the project. In our case, we are going to put the cluster name as "jhooq-springboot-gc"

Create new project on google cloud platform

After click that you should be able to create the project and it should be visible under your project section

Project name inside google cloud plateform

2. Create Kubernetes Cluster on Google Cloud

Now after creating the project, we need to setup/create kubernetes cluster

Setting up or creating a new cluster inside the Google Cloud Platform(GCP) is pretty simple and it can be done with few clicks and some information.

If you haven't selected your project then please do select from "My First Project " menu. After than navigate to "Kubernetes Engine" menu in the left hand side and then click on "Cluster"

Create cluster on google cloud platform

Cluster information during cluster creating on google cloud

It should take around couple of minutes or more to setup the cluster. But Once its ready you should be able to see your cluster information as show below

Posts in this Series