Learn how to build, dockerize, and run a Spring Boot application in containers like a pro!
Introduction
Are you tired of hearing “It works on my machine”?
Docker solves this problem by packaging your app with all its dependencies into a portable container.
In this step-by-step guide, we’ll show you how to containerize a Spring Boot application using Docker. Whether you’re a beginner or an intermediate developer, this tutorial will help you understand exactly what goes on behind the scenes — from creating a Dockerfile to running your Java app in an isolated environment.
By the end of this guide, you’ll have your Spring Boot app running inside Docker, ready for production deployment.
Prerequisites
Before you begin, make sure you have:
- Java 21
- Spring Boot project (we’ll use Maven)
- Docker installed (Download Docker)
Step 1: Create a Simple Spring Boot Application
If you don’t already have a Spring Boot project, go to start.spring.io and create one with:
- Project: Maven
- Dependencies: Spring Web
- Java: 21
Create a simple controller:
@RestController
public class HelloController {
@GetMapping("/")
public String home() {
return "Hello from Spring Boot + Docker!";
}
}
Build the JAR file using:
./mvnw clean package
Step 2: Create a Dockerfile
In the root of your project, create a file named Dockerfile
:
# Use a lightweight OpenJDK base image
FROM openjdk:21-jdk-slim
# Set working directory
WORKDIR /app
# Copy the jar file
COPY target/*.jar app.jar
# Expose the port the app runs on
EXPOSE 8080
# Run the application
ENTRYPOINT ["java", "-jar", "app.jar"]
This tells Docker:
- Use a Java 21 base image
- Copy your compiled
.jar
file - Run it using
java -jar
Step 3: Build the Docker Image
In your terminal, run:
docker build -t springboot-docker-demo .
This builds an image with the tag springboot-docker-demo
.
Step 4: Run Your Dockerized App
Now run the container:
docker run -p 8080:8080 springboot-docker-demo
Visit http://localhost:8080 — and you’ll see:
Hello from Spring Boot + Docker!
Boom! Your app is now running in a Docker container.
Step 5: Verify It Works
You can check running containers:
docker ps
To stop:
docker stop <container_id>
Bonus: Push to Docker Hub (Optional)
Want to share your image?
- Login to Docker:
docker login
- Tag your image:
docker tag springboot-docker-demo your-dockerhub-username/springboot-docker-demo
- Push it:
docker push your-dockerhub-username/springboot-docker-demo
Conclusion
You’ve now containerized your first Spring Boot app like a pro.
Docker makes it easier to deploy and scale applications in any environment — from your laptop to the cloud.
Final Words
Building robust applications is just the beginning — packaging them smartly is what makes you a pro.