Spring Boot Applications with Docker and Kubernetes

Tuanh.netTuanh.net
2 min read

1. Introduction

Spring Boot is a popular framework for building microservices and standalone applications. Docker provides containerization for consistent environments, while Kubernetes offers orchestration and management at scale.

2. Setting Up Your Spring Boot Application

2.1 Creating a Sample Spring Boot Application

Let's create a simple Spring Boot application to demonstrate the deployment process.

Use Spring Initializr (https://start.spring.io) to create a new project with dependencies for Spring Web and Spring Boot DevTools. Name the project demo.

2.2 Define the Application

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

2.3 Create a Simple REST Controller

package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class GreetingController {

@GetMapping("/greet")
public String greet() {
return "Hello, World!";
}
}

2.4 Build the Application

Run the following command to build the application:

./mvnw clean package

3. Dockerizing the Spring Boot Application

3.1 Create a Dockerfile

Create a file named Dockerfile in the root of your project:

# Use the official OpenJDK image
FROM openjdk:17-jdk-slim

# Set the working directory
WORKDIR /app
# Copy the JAR file into the container
COPY target/demo-0.0.1-SNAPSHOT.jar app.jar

# Run the JAR file
ENTRYPOINT ["java", "-jar", "/app/app.jar"]

3.2 Build the Docker Image

docker build -t demo-app .

3.3 Run the Docker Container

Run the Docker container with the following command:

docker run -p 8080:8080 demo-app

Read more at : Spring Boot Applications with Docker and Kubernetes

0
Subscribe to my newsletter

Read articles from Tuanh.net directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Tuanh.net
Tuanh.net