Developing Spring Boot Microservices Using Docker and Kubernetes: A Comprehensive Guide

Developing Spring Boot Microservices Using Docker and Kubernetes: A Comprehensive Guide

In this step-by-step guide, we will show you how to develop Spring Boot Microservices using Kubernetes and Docker. You will learn how to set up a development environment, create a Spring Boot application, build a Docker image, push the image to Docker Hub, deploy the application to Kubernetes, and expose it to the internet. By the end of this guide, you will have a clear understanding of how to develop and deploy Microservices using the latest technologies.

System Requirements

Before we begin, make sure you have the following installed on your system:

  • Java 8 or later

  • Maven

  • Docker Desktop

  • Kubernetes

  • Postman

Introduction

Spring Boot

Spring Boot is a Java-based open-source framework that helps developers build production-grade applications. It provides a range of features like auto-configuration, simplified dependency management, embedded servers, and many more.

Microservices architecture

Microservices architecture is an approach to building large and complex applications by breaking them down into smaller and independent services. These services are built and deployed independently, allowing for better scalability, fault tolerance, and maintainability.

Docker

Docker is a containerization platform that allows you to package and deploy your applications in containers. Docker containers are lightweight, portable, and provide a consistent environment to run your applications.

Kubernetes

Kubernetes is an open-source container orchestration platform that helps you manage and deploy containerized applications. It provides features like automatic scaling, self-healing, load balancing, and many more.

Step 1: Create a Spring Boot Project

The first step is to create a new Spring Boot project using the Spring Initializr. You can do this by visiting start.spring.io and selecting the following options:

  • Project: Maven

  • Language: Java

  • Spring Boot: 2.5.x or higher

  • Group: online.techstories.demo

  • Artifact: rest-api-docker-kubernetes

  • Packaging: jar

  • Java Version: 8

  • Dependencies: Web, Spring Data JPA, Lombok

Click "Generate" to download the project.

Step 2: Create the Entity class

Firstly, we will create an entity class, which represents the data model for our microservice. For this tutorial, we will create a simple "Customer" entity class that has three properties - "id", "name", and "email".

@Entity
@Data
public class Customer {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String email;
}

In this code, we use the @Entity annotation to mark the class as an entity. We also use the Lombok @Data annotation to generate getters, setters, and other boilerplate code.

Step 3: Define the JPA repository

Next, we will create a repository class that will handle the CRUD operations for our entity. For this tutorial, we will use Spring Data JPA, which is a powerful library that provides an easy way to interact with a database.

@Repository
public interface CustomerRepository extends JpaRepository<Customer, Long> {
}

In this code, we use the @Repository annotation to mark the interface as a repository. We also extend the JpaRepository interface, which provides CRUD (Create, Read, Update, Delete) operations for our entity.

Step 4: Create a Service

In this step, we'll create a service class that defines the business logic for our microservice. For this example, we'll create a service class called CustomerService that interacts with the CustomerRepository.

@Service
public class CustomerService {
    @Autowired
    private CustomerRepository customerRepository;

    public List<Customer> getAllCustomers() {
        return customerRepository.findAll();
    }

    public Customer saveCustomer(Customer customer) {
        return customerRepository.save(customer);
    }

    public void deleteCustomer(Long id) {
        customerRepository.deleteById(id);
    }

    public Customer updateCustomer(Long id, Customer customer) {
        Customer existingCustomer = customerRepository.findById(id).orElse(null);
        if (existingCustomer != null) {
            existingCustomer.setName(customer.getName());
            existingCustomer.setEmail(customer.getEmail());
            return customerRepository.save(existingCustomer);
        }
        return null;
    }
}

Here, we have used the "@Service" annotation and autowired the repository inside the class, and created methods to perform CRUD operations on the customers.

Step 5: Build the project and Create a Jar file

In this step, we will build our project to create a jar file. Run the below command in a terminal window: -

mvn clean package

Step 6: Create a Docker Image

After creating our microservice, we will now create a Docker image for it. We will use a Dockerfile to build our image. Create the below file named "Dockerfile" in the root directory of the project.

FROM openjdk:8-jre-slim
WORKDIR /app
EXPOSE 8080
COPY target/rest-api-docker-kubernetes-0.0.1-SNAPSHOT.jar /app
ENTRYPOINT ["java", "-jar", "rest-api-docker-kubernetes-0.0.1-SNAPSHOT.jar"]

This Dockerfile specifies that we want to use the OpenJDK 8 image from Docker Hub as the base image. We then copy the compiled JAR file to the image and set it as the entry point to run when the image is started.

Now we can build the Docker image by running the following command in the root directory of the project:

docker build -t restapidockerkubernetes:1.0 .

Step 7: Push the Docker Image to Docker Hub

We'll now push the Docker image to Docker Hub so that we can use it to deploy our application to Kubernetes. First, we need to create a Docker Hub account if we don't already have one. Then, we need to log in to Docker Hub from the command line using the following command:

docker login

Enter the username and password for the Docker Hub account when prompted.

Now we can tag the Docker image with our Docker Hub username and push it to Docker Hub using the following commands:

docker tag restapidockerkubernetes:1.0 beingsujeetk/restapidockerkubernetes:1.0

docker push beingsujeetk/restapidockerkubernetes:1.0
Note
Ensure to replace "beingsujeetk" with your Docker Hub username.

Step 8: Create a Kubernetes Deployment

We'll now create a Kubernetes deployment manifest to define how our application should be deployed to a Kubernetes cluster. Create a new file called "restapidockerkubernetes-deployment.yaml" in the root directory of the project and add the following content:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: restapidockerkubernetes-deployment
spec:
  replicas: 1
  selector:
    matchLabels:
      app: restapidockerkubernetes
  template:
    metadata:
      labels:
        app: restapidockerkubernetes
    spec:
      containers:
        - name: restapidockerkubernetes-container
          image: beingsujeetk/restapidockerkubernetes:1.0
          resources:
            limits:
              cpu: "1"
              memory: "512Mi"
            requests:
              cpu: "0.5"
              memory: "256Mi"
          ports:
            - containerPort: 8080

This manifest specifies that we want to deploy one replica of our application, with a label selector to identify our application's pods.

Note
Ensure to replace "beingsujeetk" with your Docker Hub username.

Next, apply this manifest to your Kubernetes cluster by running the following command:

kubectl apply -f restapidockerkubernetes-deployment.yaml

To check the status of the deployment, run the below command:

kubectl get deployments

Step 10: Create a Kubernetes Service

In order to expose the deployed microservice to the outside world, we need to create a Kubernetes service. A service is an abstraction layer that provides a static IP address and DNS name for the deployed microservice.

Create a new file called "restapidockerkubernetes-service.yaml" in the root directory of the project and add the following content:

apiVersion: v1
kind: Service
metadata:
  name: restapidockerkubernetes-service
spec:
  selector:
    app: restapidockerkubernetes
  ports:
    - name: http
      protocol: TCP
      port: 8080
      targetPort: 8080
  type: LoadBalancer

This manifest exposes the application on port 80 and routes traffic to port 8080 on the pods running the application.

Next, apply the service manifest to the Kubernetes cluster using the following command:

kubectl apply -f restapidockerkubernetes-service.yaml

This will create a service and expose it to the outside world.

To check the status of the service and endpoint, run the below command:

kubectl get services

To check the status of the pods, run the below command:

kubectl get pods

Step 11: Test the Service using Postman

Finally, we can test our microservice by sending a request to the service using Postman. You can download Postman from postman.com/downloads.

  1. Open Postman and create a new request.

  2. Set the request method to GET and the request URL to the public IP address of the load balancer we created earlier, followed by "/customers" (e.g. localhost/customers).

  3. Send the request and verify that the response contains an empty JSON array.

Similarly, you can test the other endpoints to create and update a Customer.

That's it! You have successfully developed a Spring Boot microservice using Kubernetes and Docker. You can now scale your microservice up or down, deploy it to multiple environments, and easily manage it using Kubernetes.

Conclusion

In this tutorial, we have seen how to develop a Spring Boot microservice using Kubernetes and Docker. We have covered the basics of Spring Boot, microservices architecture, Docker, and Kubernetes, and seen how to create a Docker image, push it to Docker Hub, create a Kubernetes deployment manifest and service manifest, and deploy the microservice to Kubernetes.

By using Spring Boot for Docker and Kubernetes, you can develop cloud-native applications that are scalable, resilient, and easy to manage. You can also easily deploy your applications to multiple environments, including on-premise and cloud environments, and take advantage of the benefits of cloud-native development with Spring Boot.

GitHub Code

Please refer to the below GitHub location for the completed project.

https://github.com/BeingSujeetK/techstories-demo-spring-boot/tree/main/springboot-rest-api-with-docker-and-kubernetes

Did you find this article valuable?

Support Sujeet Kumar by becoming a sponsor. Any amount is appreciated!