{{announcement.body}}
{{announcement.title}}

Running Spring Boot Application on Kubernetes Minikube on Windows (Part 1)

DZone 's Guide to

Running Spring Boot Application on Kubernetes Minikube on Windows (Part 1)

Learn more about running Spring Boot applications on Kubernetes in Windows.

· Java Zone ·
Free Resource

Windows on large building

Learn more about running Spring Boot applications on Kubernetes in Windows.

This is part one of the series "Running a Spring Boot Application on Kubernetes Minikube in Windows." This article assumes that the reader has previous experience with Spring Boot, containers, and Kubernetes. I will try and touch upon all of them in this post. After finishing this series, the reader will be able to:

1.    Create a Spring Boot application

2.   Create a Docker image for the application and store the image on Docker Hub

3.    Install minikube on your Windows Workstation and run the Spring Boot Docker image in it

You may also like: A Quick Guide to Microservices With Kubernetes, Spring Boot 2.0, and Docker

In the first part of this series, we will be creating a Spring Boot application and dockerizing it. We are assuming that the workstation to be used has Windows 10 or higher, at least 8 GB RAM and 100 GB hard disk. Let's get started!

Creating a Spring Boot Application

The following sections provide steps to create a Spring Boot app with RESTful services. Check it out.

An Introduction to Spring Boot

Spring Boot is Spring's solution to the convention-over-configuration paradigm where we need rapid application development for production-grade, Spring-based applications. Spring Boot takes care of many configurations, thereby allowing the developer to focus mostly on the code.

Spring Boot provides an in-built Tomcat engine to run web applications inside the Spring Boot sandbox itself, instead of relying on third-party application server deployment for a developer workstation. It also provides the concept of parent dependency. If you add one parent dependency to your project build file, like build.gradle (Gradle projects) or pom.xml (Maven projects), Spring Boot takes care of adding the cache of dependant libraries for the parent.

Creating Your Spring Boot Application

To create a Spring Boot application, you must have Java 8+ installed and either the Maven or Gradle build tool. You must have one IDE installed as well. 

For this project, I am using Java 8Maven, and IntelliJ IDEA: Community Edition for my IDE.

The easiest way to create a Spring Boot application from scratch is to use the Spring Boot Starter. If you visit the Spring Boot Starter project, you should be able to create the structure of your project with a basic folder structure — one Spring Boot Starter Main class and a required build file. Your build file will either be a build.gradle or a pom.xml based on the project type you chose. 

In the artifact section and group section, enter the details as required. In the dependency section, choose the Spring dependency. And lastly, for the demo project, I choose Spring Web as it would be a RESTful web application

Spring Project Initialization

After adding dependencies, click on the "Generate -Ctrl +" button. Your project will be downloaded as a .zip file. Extract the .zip file in a workspace folder. You could extract it in C:\Users\[username]\workspace folder.  Next, start IntelliJ IDEA. IntelliJ may ask you to open a project. Choose your project root folder to open the project in the IDE.

The project will have a KubeDemoApplication.java, pom.xml, and mvnw.cmd file. The structure will look similar to the image below if you opened it in IntelliJ IDEA.

Initial Kube Demo Structure

Now, we need to create a few more files to make it a web application.

POJO Class Kube

Create one Kube.java file, as shown below, in the com.example.minikube.demo.kubedemo package.

package com.example.minikube.demo.kubedemo; 
import java.io.Serializable;
import java.util.Objects;
public class Kube implements Serializable {

    private String name;
    private float length;
    private float breadth;
    private float height;
    private long id;

    public Kube(String name, float length, float breadth, float height) {
        this.name = name;
        this.length = length;
        this.breadth = breadth;
        this.height = height;
    }

    public Kube() {
    }

    @Override
    public String toString() {
        return "Kube{" +
                "name='" + name + '\'' +
                ", length=" + length +
                ", breadth=" + breadth +
                ", height=" + height +
                ", id=" + id +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Kube kube = (Kube) o;
        return Float.compare(kube.length, length) == 0 &&
                Float.compare(kube.breadth, breadth) == 0 &&
                Float.compare(kube.height, height) == 0 &&
                id == kube.id &&
                Objects.equals(name, kube.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, length, breadth, height, id);
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public float getLength() {
        return length;
    }

    public void setLength(float length) {
        this.length = length;
    }

    public float getBreadth() {
        return breadth;
    }

    public void setBreadth(float breadth) {
        this.breadth = breadth;
    }

    public float getHeight() {
        return height;
    }

    public void setHeight(float height) {
        this.height = height;
    }
}


REST Controller

Now, we would like to add one Spring REST Controller to support our CRUD RESTful operations. The filename will be KubeController.java.

package com.example.minikube.demo.kubedemo; 

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

@RestController
public class KubeController {

    private HashMap<Long,Kube> repository  = new HashMap<Long,Kube>();
    private long localId = 0l;

    @GetMapping
    public ResponseEntity index(){
        return new ResponseEntity(repository.values(), HttpStatus.OK);
    }

    @GetMapping("{id}")
    public ResponseEntity get(@PathVariable Long id){
        return new ResponseEntity(repository.get(id),HttpStatus.OK);
    }

    @PostMapping
    public String create(@RequestBody Kube kube){
        kube.setId(++localId);
        repository.put(kube.getId(),kube);
        return "Kube "+kube+" Created";
    }

    @PutMapping("{id}")
    public ResponseEntity update(@RequestBody Kube kube, @PathVariable Long id){
        if(repository.containsKey(id)){
            kube.setId(id);
            repository.replace(id,kube);
        }

        return new ResponseEntity(kube,HttpStatus.OK);
    }

    @DeleteMapping("{id}")
    public String remove(@PathVariable Long id){
        repository.remove(id);
        return "Kube having ID = "+id+ " is removed";
    }
}


Validation for the RESTful Application

Since we are done creating the REST service, we need to validate whether or not the service is working correctly. It involves starting the application and making a call to the RESTful services using the cURL or postman tool. cURL is a command-line tool that makes HTTP calls, whereas postman is a desktop tool used to test RESTful services. I will be using cURL for my tests.

Starting the Application

To start the application, open a command prompt and make your project root folder as your current directory. Type the command mvnw spring-boot:run. This would start the application at port 8080. You could see the successful start-up message in the command prompt in a few seconds.

Spring Boot Start

Validating RESTful Services

The REST API has five endpoints: 2 GET(1 for a list and 1 for by ID) and 1 POST, PUT, and DELETE each. 

POST 

Give the following command in the command prompt. It would create one Kube object. If you repeat the command by changing the values in the JSON input section, it would create multiple Kube Objects.

curl -H "Content-Type: application/json" -X POST -d {\"name\":\"triangle\",\"length\":8.5,\"breadth\":2.5,\"height\":4.5} http://localhost:8080/


GET

The GET command for a list and GET for ID will be as follows:

GET all - curl http://localhost:8080 GET By ID - curl http://localhost:8080/1


PUT

the PUT command is used to update one object.

curl -H "Content-Type: application/json" -X PUT -d {\"name\":\"triangle\",\"length\":6.5,\"breadth\":3.5,\"height\":1.5} http://localhost:8080/1


DELETE 

The DELETE command is used to delete a Kube object by id:

curl -H "Content-Type: application/json" -X DELETE http://localhost:8080/1


We need to make a GET call after the UPDATE and DELETE calls to validate whether both the commands worked fine.

Dockerization

Once we have validated that the application is working fine, we need to create a Docker image and publish it to Docker hub. Check out the following steps:

  1. Create a Docker account if you have not already

  2. Install Docker Toolbox for Windows 

  3. Create a Dockerfile 

  4. Create a Docker image of the Spring Boot application 

  5. Push the image to the Docker hub

Docker

Docker is a Platform as a Service product that enables OS-level virtualization to run applications in isolated self-dependant sandboxes called containers. Now, the container is synonymous with Docker.

Creating a Docker Account

A Docker account could be created in Docker Hub. After an account is created, create one repository under the Docker Hub. Name the repository: kube.

Install Docker Toolbox

Docker toolbox could be downloaded from the GitHub repository. Once the .exe is downloaded, it could be installed like any other .exe file. Once it is installed, start the Docker service. If the Docker service is not running, the following steps will not work.

Dockerfile

A Dockerfile is an input to Docker on how to create an image. We need to create a file inside our Spring Boot application root project and name it Dockerfile without any extension.

FROM openjdk:8-jdk-alpine 
VOLUME C:\\Users\adity\\workspace 
COPY target/kube-demo-0.0.1-SNAPSHOT.jar app.jar 
ENTRYPOINT ["java","-jar","/app.jar"]


In the above file, the volume component must be changed according to the folder structure in your work station.

Creating a Docker Image

Now, it is time to create a Docker image. First, open the command prompt and make the Spring Boot project your current directory. Give the command "mvnw package" to create the minikube-demo-0.0.1-SNAPSHOT.jar under the target folder. 

After that use the docker login command to log in to Docker Hub from the command prompt. Once the Docker login is successful, we need to create the image by giving the following command:

docker build --build-arg=target\kube-demo-0.0.1-SNAPSHOT.jar -t <docker_user_name>/<docker_repo_name>:kubedemo1


You need to put your correct docker user name and docker hub repository name. You could validate the image creation by using the docker images command. It will list all local Docker images present in your workstation. The output of the command is shown in the image in the section below.

Running the Docker Image

Once the Docker image is available, you can start the Spring Boot application in a Docker container using the following command.

docker run -p 8080:8080 adityapratapbhuyan/aditya-test:kubedemo1


The output for the Docker image and Docker run is shown below:

Docker Image and Running

Once it is running, we can test it by giving the docker-machine IP and port. To know the docker-machine IP, type the command docker-machine ip. It will give you the IP address of the Docker container. Now, we can test the application by hitting http://docker-machine-ip:8080 instead of http://localhost:8080.

Pushing the Docker Image

The Docker image can be pushed to the Docker Hub repository with the following command:

docker push adityapratapbhuyan/aditya-test:kubedemo1


Once it is pushed to the Docker Hub, you can verify it by logging into Docker Hub. Once it is available in Docker Hub, we can pull the image in any machine and run it.

Conclusion

Stay tuned for the second part of this series where we teach you how to run the image in a minikube environment on the Windows platform. We hope you enjoyed!

Further Reading

A Quick Guide to Microservices With Kubernetes, Spring Boot 2.0, and Docker

Build and Deploy a Spring Boot App on Minikube

Topics:
minikube ,kubernetes ,spring boot ,docker ,container ,maven ,restful api ,curl ,java

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}