0
0
Spring Bootframework~30 mins

Multi-stage Docker builds in Spring Boot - Mini Project: Build & Apply

Choose your learning style9 modes available
Multi-stage Docker builds with Spring Boot
📖 Scenario: You are creating a Docker image for a Spring Boot application. To keep the image small and efficient, you will use a multi-stage Docker build. This means you first build the application in one stage, then copy only the necessary files to a smaller runtime image.
🎯 Goal: Build a multi-stage Dockerfile that compiles a Spring Boot app using Maven in the first stage, then copies the built jar to a smaller OpenJDK runtime image in the second stage.
📋 What You'll Learn
Use maven:3.9.0-eclipse-temurin-17 as the build stage base image
Run mvn clean package to build the Spring Boot jar
Use eclipse-temurin:17-jre as the runtime stage base image
Copy the jar from the build stage to the runtime stage
Set the ENTRYPOINT to run the jar with java -jar
💡 Why This Matters
🌍 Real World
Multi-stage Docker builds help create smaller, efficient container images by separating build and runtime environments. This is common in real-world Spring Boot deployments.
💼 Career
Understanding multi-stage Docker builds is essential for developers and DevOps engineers to optimize container images and improve deployment workflows.
Progress0 / 4 steps
1
Create the build stage
Write the first stage of the Dockerfile named build using the base image maven:3.9.0-eclipse-temurin-17. Set the working directory to /app. Copy the pom.xml and src folder into /app.
Spring Boot
Need a hint?

Use FROM to specify the base image and name the stage build. Use WORKDIR to set the directory. Use COPY to copy files.

2
Add the build command
In the build stage, add a command to run mvn clean package to build the Spring Boot jar.
Spring Boot
Need a hint?

Use RUN to execute the Maven build command inside the container.

3
Create the runtime stage and copy the jar
Create a second stage named runtime using the base image eclipse-temurin:17-jre. Set the working directory to /app. Copy the built jar file target/demo-0.0.1-SNAPSHOT.jar from the build stage to /app/app.jar in the runtime stage.
Spring Boot
Need a hint?

Use FROM to start the runtime stage. Use COPY --from=build to copy the jar from the build stage.

4
Set the entrypoint to run the jar
In the runtime stage, add an ENTRYPOINT instruction to run the jar file with java -jar /app/app.jar.
Spring Boot
Need a hint?

Use the JSON array syntax for ENTRYPOINT to run the jar file.