Dockerizing a Spring Boot Application
Spring Boot with Docker
This guide walks you through the process of building a Docker image for running a Spring Boot application.
What You Will Need
- JDK 17
- Maven
- Docker
Starting with Spring Initializr
You can use this pre-initialized project and click Generate to download a ZIP file. This project is configured to fit the examples in this tutorial.
To manually initialize the project:
- Navigate to https://start.spring.io.
- Choose Maven and the language you want to use. This guide assumes that you chose Java.
- Click Dependencies and select Spring Web.
- Click Generate.
Set up a Spring Boot Application
Now you can update the DemoApplication.java:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@RequestMapping("/")
public String home() {
return "Hello World!";
}
}
Containerize It
Create the following Dockerfile in your Spring Boot project:
FROM maven:3.8.5-openjdk-17 as build
WORKDIR /app
COPY pom.xml .
RUN mvn dependency:go-offline -DskipTests
COPY src src
RUN mvn clean package
FROM openjdk:17
COPY --from=build /app/target/*.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java","-jar","/app.jar"]
Build the Docker Image
docker build -t demo:latest .
Run the Container
docker run -p 8080:8080 demo:latest
Now you can visit http://localhost:8080
You can download the source code here