Spring Boot Microservices on Kubernetes | OnlineITGuru
Click to rate this post!
[Total: 1 Average: 2]

An application is responsible for serving various services to many users across the globe. And these services were internally divided into several other internal services.  And if everything goes well, then the developers would deploy these services on different tools. For instance, developers these microservices, on Kubernetes. Moreover, developers today opt for a different framework like JAVA Spring to develop this kind of service. Hence today, in this article, I’m going to explain the utilization of Spring Boot MicroServices on Kubernetes.

Hence,  prior to knowing the utilization of Spring Boot Microservices practically, let us initially know about the needs for spring-Boot Microservices and then move with the deployment of Microservices on Kubernetes. So without much waste of time, let us walk through one by one in detail

What are Spring boot Microservices?

Prior to knowing about the spring boot Microservices, let us initially know  about

Microservices are the design pattern that splits the larger monolithic services into small services called Microservices. All these services were loosely coupled over the network.  In a microservices architecture, all the services are fine-grained and contain the lightweight protocol.  In Microservices, each service works independently.  The major advantage of this microservice change to the specific microservice does not affect the other functioning.  Furthermore, with microservice, we can easily build, expand and scale the applications.  Abd utilizing this microservices on Spring Boot are called Spring Boot Microservices

What is Kubernetes?

Kubernetes is the platform for deploying containerized applications. You people can assume this as a  container orchestration for Docker container.  Besides, this tool allows us to write the YAML scripts. With these scripts, we people can automate the deployment of microservice architecture to our required platform. Here GKE Contains a huge project with lots to dig in. Besides, istio add another layer on top of Kubernetes. This adds great monitoring, security, access control, and the load balancing features.

And the last piece of this architecture is google Cloud and GKE. And this platform allows you to deploy the microservice. On the other hand, Minikube allows the users to run the services locally on the computer. This Minikube allows Kubernetes to work on different kinds of platform like Linux, Mac as well as Windows.

What is Spring Boot?

Spring Boot is an open-source Java framework to create the microservice. It is responsible for building the stand-alone as well as the production-ready applications. With this framework, developers can easily build applications in a short span of time. This is because the framework itself will take care of necessary configuration files for developing the application.

Hence,  we people have got a brief idea regarding Kubernetes, spring Boot and the microservices, let us move our discussion  with

Requirements for Spring boot Microservices and Kubernetes:

HTTPie:  Install this HTTPie from the official website. So that we can run the HTTP request from the terminal.

Docker: As above install this software container too from the Docker official website. (ignore this, if you have already installed)

Kubectl: Install this from the official website by following the instructions from the official ones

Google Cloud:  You will need a google cloud account with billing enabled.  Initially make the use of the free trial from Google Cloud Website

gcloud: Install this CLI to install the google cloud components.

And these are minimum things that are necessary to deploy the spring Boot-microservices on Kubernetes. And I hope, you people have this necessary software. Once you installed all those, then execute the following command

gcloud components install kubectl

And once done, now

Create a Google Kubernetes Engine project using Istio:

Now we come to the point, we need the utilize the google Cloud account with the billing enabled.  Moreover, as I mentioned to you earlier, you can utilize all the paid services in the free trial initially. So don’t waste your money by placing your card.

Once you are logged into the account, create a project with any unique name as OnlineITGuru. And once created, wait for the project ID to get created.  Once the ID gets created, you will find the project as OnlineITGuru-598685.

(Note: Remember this project ID where it requires this ID in the next steps)

Hence store it in a shell variable and makes use of it.

PROJECT_NAME=<your project name and ID>

And once the project gets created, open the project dashboard, move to the navigation menu and click on Kubernetes Engine. Click on the billing enabled if you have not enabled billing earlier and select the billing account).

Cluster Creation:

a)Click on Create Cluster

spbt cluster on kubernetes | OnlineITGuru


pick your first cluster using the left side panel.

Name the cluster as  SpringBoot Cluster.

Select your neatest zone. As of now, im selecting us-west-1a

Click on the Advanced options link at the bottom of the cluster config panel to show the advanced options.  Now scroll now and check the box for Enable istio (beta).  This will automatically install istio on the cluster.

At the bottom, click on create to create the new cluster.

(Note: Creation of cluster do takes some time.)

In the meantime, execute the following

Initialize the gcloud CLI by running the following command.

gcloud init

Once the cluster gets deployed, you need to connect your local gcloud and kubectl CLI using the following command

gcloud container clusters get-credentials {yourClusterName} --zone us-west1-a --project {yourProjectId}

Once done, you could see the following

Fetching the cluster endpoint and the auth data

kubeconfig entry generated for spring-boot-cluster

Assign yourself as admin in the cluster

kubectl create clusterrolebinding cluster-admin-binding --clusterrole=cluster-admin --user=$(gcloud config get-value core/account)

Make sure that Isthio services were installed and running.  You can check all those in different ways. Some of them were listed below

Click on Service button in google cloud platform Kubernetes engine. And for the service that you have created earlier the status should be green “OK”  under the status column.

The other to check is to use the Kubernetes CLI. Run the following command

kubectl get services --all-namespaces

In the above command, –all-namespace, is required to show the Ishtio services that were under istio system namespace.

Also, check the Kubernetes pods using the following command

To check the Kubernetes pods, use: kubectl get pods --all-namespaces
I hope you people have done till here if you stuck anywhere in the middle feel free to contact us at Spring Boot training
Create a Spring Boot Project for MicroServices:

Navigate to the spring initializer and  create your starter project

  1. Change the build tool from Maven to the Gradle
  2. Use Java and Spring Boot version 2.13
  3. update the group to com.okta.spring
  4. Utilize the articraft springbootkbe
  5. Add the required dependencies

Now click on Generate the project and download the project. And uncompress the project. And if you are new these kinds of project, you can get all those at Spring Boot-microservices examples github.

Once done execute the following code

package com.okta.spring.springbootkbe;
import lombok.AllArgsConstructor;  
import lombok.Data;  
import lombok.NoArgsConstructor;  
import org.springframework.data.mongodb.core.mapping.Document;  
public class Kayak {  
    private String name;  
    private String owner;  
    private Number value;  
    private String makeModel;  


Now create the another file under the same package KayakRepository.java 

package com.okta.spring.springbootkbe;  
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;  
public interface KayakRepository extends ReactiveMongoRepository<Kayak, Long> {  

Now add the controller to access the DOM file. For this create a file called KayakController in the com.okta.spring.springbootkbe package

package com.okta.spring.springbootkbe;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@RequestMapping(path = "/kayaks")
public class KayakController {

    private final KayakRepository kayakRepository;

    public KayakController(KayakRepository kayakRepository) {
        this.kayakRepository = kayakRepository;

    public @ResponseBody
    Mono<Kayak> addKayak(@RequestBody Kayak kayak) {
        return kayakRepository.save(kayak);
    public @ResponseBody
    Flux<Kayak> getAllKayaks() {
        Flux<Kayak> result = kayakRepository.findAll();
        return result;

This controller adds two endpoints like POST and GET endpoints which adds the new kayak and list all the kayaks. For instance, add the controller called Root Controller

package com.okta.spring.springbootkbe;  
import org.springframework.stereotype.Controller;  
import org.springframework.web.bind.annotation.*;  
import reactor.core.publisher.Flux;  
public class RootController {  
    public Flux<String> getRoot() {  
      return Flux.just("Alive");  

The above controller is responsible for performing the health checks on the root endpoints of the services and needs to return the response. If not the cluster will shutdown. And in order to bootstrap the sample data with the sample database, update the springbootkbeapplication class definition.

package com.okta.spring.springbootkbe;  
import org.springframework.boot.ApplicationRunner;  
import org.springframework.boot.SpringApplication;  
import org.springframework.boot.autoconfigure.SpringBootApplication;  
import org.springframework.context.annotation.Bean;  
import reactor.core.publisher.Flux;  
public class SpringbootkbeApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootkbeApplication.class, args);

    ApplicationRunner init(KayakRepository repository) {

        Object[][] data = {
            {"sea", "Andrew", 300.12, "NDK"},
            {"creek", "Andrew", 100.75, "Piranha"},
            {"loaner", "Andrew", 75, "Necky"}

        return args -> {
                        .map(array -> {
                            return new Kayak((String) array[0], (String) array[1], (Number) array[2], (String) array[3]);
                .subscribe(kayak -> System.out.println("saving " + kayak.toString()));


Now add the dependencies to the build.gradle file

compile 'de.flapdoodle.embed:de.flapdoodle.embed.mongo'

Run the springboot application using gradle bootRun

Then you see the output bunch as shown below

2019-02-14 19:29:34.941  INFO 35982 --- [ntLoopGroup-2-4] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:5, serverValue:5}] to localhost:61858
2019-02-14 19:29:34.946  INFO 35982 --- [ntLoopGroup-2-3] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:4, serverValue:4}] to localhost:61858
saving Kayak(name=sea, owner=Andrew, value=300.12, makeModel=NDK)
saving Kayak(name=loaner, owner=Andrew, value=75, makeModel=Necky)
saving Kayak(name=creek, owner=Andrew, value=100.75, makeModel=Piranha)

Use httpie to test the app http:8080

HTTP/1.1 200 OK
Content-Type: text/plain;charset=UTF-8
transfer-encoding: chunked


Also get your endpoints using http:8080/kayaks

HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
transfer-encoding: chunked
    "makeModel": "NDK",
    "name": "sea",
    "owner": "Andrew",
    "value": 300.12
    "makeModel": "Necky",
    "name": "loaner",
    "owner": "Andrew",
    "value": 75
    "makeModel": "Piranha",
    "name": "creek",
    "owner": "Andrew",
    "value": 100.75
Deploy MongoDB Kubernetes pod for using spring boot:

Kubernetes works by deploying docker containers using YAML scripts. For this create  deployment-mongo.yml in your projects root directory

apiVersion: apps/v1  
kind: Deployment  
  name: mongodb  
    appdb: mongodb  
  replicas: 1  
      appdb: mongodb  
        appdb: mongodb  
        - name: mongodb  
          image: mongo:3.6.6  
            - containerPort: 27017  
apiVersion: v1  
kind: Service  
  name: mongodb  
    app: mongodb  
    - port: 27017  
      protocol: TCP  
    appdb: mongodb

Thus this defines the MongoDB Kubernetes cluster deployment  and the service to create the Mongo Database on the Cluster.  And now, we will see

Would you like to learn Kubernetes, then enroll now at Kubernetes online Training

How to deploy Spring Boot app to the cluster?

create and add a file named docker file in the root directory

FROM openjdk:8-jdk-alpine  
ENV APP_FILE springbootkbe-0.0.1-SNAPSHOT.jar  
ENV APP_HOME /usr/app  
EXPOSE 8000  
COPY build/libs/*.jar $APP_HOME/  
ENTRYPOINT ["sh", "-c"]  
CMD ["exec java -jar $APP_FILE"]

update the file at  src/main/resources/application.properties:

And this configures the Spring Boot port that you are exposing the dockerfile as well as configuring the MongoDB host and the port. Usually by default, the hostname is the name of the service running inside the cluster.
And now build your app using the following commands
gradle clean build

And now create another Kubernetes deployment script called deployment.yml in the root directory.

apiVersion: v1  
kind: Service  
  name: kayak-service  
    app: kayak-service  
    - name: http  
      port: 8000  
    app: kayak-service  
apiVersion: extensions/v1beta1  
kind: Deployment  
  name: kayak-service  
  replicas: 1  
        app: kayak-service  
        version: v1  
        - name: kayak-app  
          image: gcr.io/spring-boot-gke-<id>/kayak-app:1.0  
          imagePullPolicy: IfNotPresent  
            - name: MONGODB_HOST  
              value: mongodb  
            - containerPort: 8000  
              path: /  
              port: 8000  
            initialDelaySeconds: 5  
            periodSeconds: 5

Configure the Google Cloud and docker using the following command

gcloud auth configure-docker

Build the docker image

docker build -t kayak-app:1.0 .

Tag the image and push it to the google container registry.

docker tag kayak-app:1.0 gcr.io/$PROJECT_NAME/kayak-app:1.0;  
docker push gcr.io/$PROJECT_NAME/kayak-app:1.0

Apply deployment.yml file to the GKE Cluster

kubectl apply -f deployment.yml

And make sure pod is deployed properly

kubectl get pods
NAME                             READY     STATUS    RESTARTS   AGE
kayak-service-7df4fb9c88-srqkr   1/1       Running   0          56s
mongodb-c5b8bf947-dmghb          1/1       Running   0          16m

But this file is not accessible to the public

So create file called istio-gateway.yml

apiVersion: networking.istio.io/v1alpha3  
kind: Gateway  
  name: kayak-gateway  
    istio: ingressgateway # use Istio default gateway implementation  
  - port:  
      name: http  
      number: 80  
      protocol: HTTP  
    - '*'  
apiVersion: networking.istio.io/v1alpha3  
kind: VirtualService  
  name: kayak-service  
  - "*"  
  - kayak-gateway  
  - match:  
    - uri:  
        prefix: /  
    - destination:  
          number: 8000  
        host: kayak-service

And apply the following command.

 kubectl apply -f istio-gateway.yml

Once applied, you will be getting the output as

gateway.networking.istio.io "kayak-gateway" created
virtualservice.networking.istio.io "kayak-service" created

And if you got the same, you are INN.

Hence like we used to deploy the Spring Boot-microservices on Kubernetes cluster. And like this, developers utilize this Spring Boot-microservices on the Kubernetes. And I hope you people have got a brief idea regarding the deployment of Spring Boot-microservices on Kubernetes. Get the practical explanation of all these at Spring Boot online training 

Drop Us A Query

100% Secure Payments. All major credit & debit cards accepted.

Call Now Button