Let’s get started with Docker by building a simple Spring Boot project using Spring Initializer and Dockerizing it step by step.
Github Project link – https://github.com/kuldeep101990/Spring-docker-demo
Step 1: Create a Spring Boot Project
- Go to Spring Initializer.
- Configure the project:
- Project: Maven
- Language: Java
- Spring Boot Version: Latest stable version
- Dependencies: Add
Spring Web
andSpring Boot DevTools
- Group:
com.example
- Artifact:
docker-demo
- Name:
docker-demo
- Click Generate to download the project, extract it, and open it in your IDE.
Step 2: Add a Simple REST Endpoint
- Create a new package
com.example.dockerdemo.controller
. - Add a class
HelloController
:
package com.example.dockerdemo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello, Docker!";
}
}
- Run the application and test it:
- Run the project in your IDE or using
./mvnw spring-boot:run
. - Open your browser or use Postman to visit:
http://localhost:8080/hello
.
- Run the project in your IDE or using
Step 3: Create a Dockerfile
- In the root of your project, create a file named
Dockerfile
(no extension). - Add the following content:
# Use an official Java runtime as a parent image
FROM openjdk:17-jdk-slim
# Set the working directory
WORKDIR /app
# Copy the built JAR file to the container
COPY target/docker-demo-0.0.1-SNAPSHOT.jar app.jar
# Expose the application port
EXPOSE 8080
# Run the application
ENTRYPOINT ["java", "-jar", "app.jar"]
Step 4: Build the Spring Boot Application
- Open your terminal in the project root.
- Run:
./mvnw clean package
- Ensure the
target
folder contains thedocker-demo-0.0.1-SNAPSHOT.jar
file.
Step 5: Build and Run the Docker Image
- Build the Docker image:
docker build -t docker-demo .
- Run the Docker container:
docker run -p 8080:8080 docker-demo
- Test your application:
- Visit
http://localhost:8080/hello
to see the “Hello, Docker!” message.
- Visit
Step 6: Stop and Remove the Container
- List running containers:
docker ps
- Stop the container:
docker stop <container-id>
- Remove the container:
docker rm <container-id>
Let me know when you’re ready for more advanced Docker features like Docker Compose or multi-stage builds! π