Open In App

Containerizing Spring Boot Application

Java applications, known for their robustness sometimes become difficult to deploy and manage. This is where containerization comes into the picture. Packaging your Java app into a lightweight and self-contained independent unit can provide many benefits to the developers:

In this article we will discuss the complete process of containerizing the Java application using Spring Boot App and Dockerfile, making it easier than ever to bring your Java apps to deploy. The steps involved, from setting up your Spring Boot app to building and running your very own Create Docker image as as follows:



The steps will be as follows:-

  1. Setting up a spring-boot app
  2. Create a docker image
  3. Building project jar
  4. Building a docker image by using a docker file
  5. Running image

Let’s examine the above steps in detail



Step By Step Implementation

For understanding first we will use a basic spring-boot greetings project with a single API to greet the user, with the help of a spring-boot-starter-web.

Overall we need to create these files in the directory.

1. Configuration

You can either do project configuration directly through the IDE, or you can select the below method:

Overall you only need this dependency to for the project:

// Controller layer for Testing Project
package com.example.springbootdockerdemo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Spring Boot controller class
*/
@RestController
public class HelloController {
/**
* HTTP GET requests to the root path ("/") and returns greeting message.
*
* @return message "Greetings from Spring Boot!!".
*/
@RequestMapping("/")
public String index() {
return "Greetings from Spring Boot!!";
}
}

To run this app use command:

mvn spring-boot:run

3. Creating A Dockerfile for Application

A dockerfile is a text document which contains commands read by docker and is executed in order to build a container image.

FROM java:8-jdk-alpine
COPY target/spring-boot-docker-demo-0.0.1-SNAPSHOT.jar /usr/app/
WORKDIR /usr/app
RUN sh -c 'touch spring-boot-docker-demo-0.0.1-SNAPSHOT.jar'
ENTRYPOINT ["java","-jar","spring-boot-docker-demo-0.0.1-SNAPSHOT.jar"]

Explanation of docker file:

Building Project Jar

Now run mvn install to build a .jar file in target directory.

mvn install

Building Docker Image

Execute the below command to complete the build of Docker Image

docker build -t spring-boot-docker-demo

Run the image build

Execute the below command to complete the image build

docker run spring-boot-docker-demo

Conclusion

Now we have a portable, self-sufficient unit making Spring Boot application containerized using Docker now these application can be easily used across different environments-

Containerization plays key importance in build and deploying applications.

Article Tags :