Hey there, Spring Boot lovers! π±
Ever wondered how to wrap your awesome Spring Boot app in a Docker container and make it run anywhereβlike magic? πͺ
Youβre in the right place! In this guide, weβll go step-by-step to Dockerize your Spring Boot app and help you feel like a DevOps superhero π¦Έ.
π§ What Youβll Learn
- What Docker is (super simply)
- How to create a Dockerfile for Spring Boot
- How to build and run your Docker container
- How to smile while doing it π
π¦ Step 1: Whatβs Docker Anyway?
Imagine youβre sending your app to a friend. You donβt want to tell them to install Java, download dependencies, and fix bugs from βit works on my machine.β π
Docker solves that by putting everything your app needs in one box β called a container.
Think of it like a lunchbox for your app. π±
βοΈ Step 2: Create a Simple Spring Boot App
If you already have one, skip this part. If not:
- Go to https://start.spring.io
- Choose:
- Project: Maven
- Language: Java
- Spring Boot: Latest
- Dependencies: Spring Web
- Click Generate, unzip the project, and open it in your IDE (like IntelliJ or VS Code)
Then create a simple controller:
@RestController public class HelloController { @GetMapping("/") public String hello() { return "Hello from Dockerized Spring Boot! π’"; } }
π§Ύ Step 3: Add a Dockerfile
In the root of your project, create a file called Dockerfile
(no file extension).
# Start from an official Java image FROM openjdk:21-jdk-slim # Set the working directory WORKDIR /app # Copy the built JAR file COPY target/*.jar app.jar # Expose port 8080 EXPOSE 8080 # Run the app ENTRYPOINT ["java", "-jar", "app.jar"]
β Make sure your app is built first by running:
./mvnw clean package
You should get a file like: target/your-app-name-0.0.1-SNAPSHOT.jar
.
π οΈ Step 4: Build the Docker Image
Now let's build the Docker image (like baking the lunchbox):
docker build -t spring-boot-docker .
π·οΈ
-t spring-boot-docker
gives your image a name.
π Step 5: Run the Container
Now run your app inside Docker:
docker run -p 8080:8080 spring-boot-docker
Now open your browser and visit:
http://localhost:8080
π You should see:
Hello from Dockerized Spring Boot! π’
π‘ Bonus Tips
- You can push your image to Docker Hub to share with the world.
- Want to rebuild? Use
docker build --no-cache -t spring-boot-docker .
- Check running containers with
docker ps
- Stop containers with
docker stop <container_id>
π§ Wrapping It Up
Now youβve got a portable, reliable, and awesome Dockerized Spring Boot app! π
You just unlocked the superpower of deploying your Java backend anywhere β on your VPS, cloud server, or even a Raspberry Pi π.
βDocker is like a box of chocolates. You always know what you're gonna get.β π«
Top comments (0)