Welcome back! In the previous lesson, we made our microservices observable by adding production-grade health checks with Spring Boot Actuator. We defined liveness and readiness probes, which are critical for running our application in an orchestrated environment like Kubernetes.
So far, our services are still just Java processes running directly on our local machine. To prepare them for deployment, we need to package them into a standard, portable, and isolated format. This is where Docker comes in.
In this lesson, you will write a multi-stage Dockerfile to create an optimized, production-ready container image for a Spring Boot application. This is a foundational skill for any modern backend or platform engineer.
MERN Stack Comparison
In the MERN world, you've likely written a Dockerfile for a Node.js application. The process is conceptually similar: start with a base image (e.g., node:18-alpine), copy your package.json, install dependencies with npm install, copy your source code, and define a command to start the server.
The core challenge we'll tackle today is how to do this efficiently for a compiled language like Java. A naive approach leads to very large images and slow build times. Our goal is to create a small, secure, and well-cached image, which is a hallmark of a production-grade system.
1. The Problem: The Naive Dockerfile
Many initial attempts to containerize a Spring Boot application result in a Dockerfile that works but is highly inefficient.
A naive Dockerfile might look like this (you don't need to create this file):
# (Don't use this - it's inefficient!)
FROM maven:3.8-jdk-17
# Copy the entire project source code
WORKDIR /app
COPY . .
# Build the application inside the container
RUN mvn clean package -DskipTests
# Run the application
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "target/blog-service-0.0.1-SNAPSHOT.jar"]
This approach has two major problems:
- Huge Image Size: The final image contains the full Maven and JDK environment, including your source code and build artifacts, which are not needed to simply run the application. This can result in an image size of nearly 1 GB.
- Poor Caching: Any change to your source code, no matter how small, requires Docker to re-run the
mvn packagecommand and invalidates the cache for this layer and all subsequent layers. This means rebuilding and re-pushing a massive image for every minor change.
To understand why this happens, it's essential to grasp how Docker layers and caching work.
Optimizing Spring Boot apps for Docker by Mike Thompson, Graham Charters
The video 'Optimizing Spring Boot apps for Docker' from Devoxx provides an excellent explanation of Docker layers and why the simple approach is so inefficient.
Please watch from 02:04 to 09:09. The speakers will walk through a basic Dockerfile, explain how layers and caching work, and then demonstrate why the resulting application layer is so large.
2. The Solution: Multi-Stage Builds
The solution to the "fat image" problem is the multi-stage build. This technique uses multiple FROM instructions within a single Dockerfile. Each FROM starts a new, temporary build stage. You can then selectively copy artifacts from one stage to another, leaving behind everything you don't need in the final image.
For our Spring Boot app, this means:
- Stage 1 (Builder): Use a full JDK/Maven image to compile the code and build the
.jarfile. - Stage 2 (Runtime): Start with a minimal JRE (Java Runtime Environment) image and copy only the final
.jarfile from the builder stage.
This ensures the final image is small and contains only what's necessary to run the application.
How to Containerize Spring Boot Applications with Docker
The article 'How to Containerize Spring Boot Applications with Docker' provides a fantastic, clear example of a multi-stage Dockerfile that we will adapt for our project.
Please read the following sections: Container Build Pipeline: This diagram visually explains the multi-stage concept. Basic Dockerfile: Study this example carefully. Note how it separates the build stage (aliased AS builder) from the runtime stage and uses COPY --from=builder. .dockerignore File: Understand why it's important to exclude certain files from the Docker build context.
Your Task (15 minutes): Create a Multi-Stage Dockerfile
Now, let's apply this to our blog-service.
-
Create
.dockerignore: In the root directory of theblog-serviceproject, create a new file named.dockerignore. This file prevents unnecessary files from being sent to the Docker daemon, speeding up the build and preventing accidental inclusion of secrets or local build files. Add the following content:.git .gitignore .idea/ *.iml target/ mvnw* .mvn/ -
Create
Dockerfile: In the same root directory, create a file namedDockerfile(with no extension) and add the following content:# --- Stage 1: Build the application --- # Use a specific Maven and Temurin JDK image for a reproducible build FROM maven:3.9.6-eclipse-temurin-17 AS builder # Set the working directory inside the container WORKDIR /app # Copy only the pom.xml first to leverage Docker layer caching for dependencies COPY pom.xml . # Download dependencies. This layer will only be rebuilt if pom.xml changes. RUN mvn dependency:go-offline -B # Copy the rest of the source code COPY src ./src # Build the application JAR, skipping tests as they should be run in a CI pipeline RUN mvn clean package -DskipTests # --- Stage 2: Create the final, optimized runtime image --- # Use a minimal JRE-only image based on Alpine Linux for a smaller footprint FROM eclipse-temurin:17-jre-alpine # Set the working directory WORKDIR /app # Create a non-root user for security RUN addgroup --system appgroup && adduser --system --ingroup appgroup appuser USER appuser # Copy only the built JAR file from the builder stage COPY --from=builder /app/target/*.jar app.jar # Expose the port the application runs on EXPOSE 8082 # Define the command to run the application ENTRYPOINT ["java", "-jar", "app.jar"] -
Build the Image: Open your terminal in the
blog-serviceroot directory and run the build command:docker build -t blog-service:0.0.1 . -
Runtime Observation: After the build completes, run
docker images | grep blog-service. You should see that your new image is significantly smaller (likely around 200-250MB) compared to the ~900MB image the naive approach would have created.
3. Advanced Optimization: Spring Boot Layered Jars
We've made a huge improvement, but we can do even better. With the current Dockerfile, a single line of code change in your application will cause Maven to repackage the entire app.jar. This invalidates the COPY --from=builder layer, forcing Docker to create a new layer containing the entire ~30MB jar.
Spring Boot can separate the "fat jar" into multiple layers based on how frequently they change:
dependencies(Regular library dependencies, change rarely)spring-boot-loader(Changes only with Spring Boot updates)snapshot-dependencies(Your custom snapshot dependencies, change more often)application(Your own code, changes constantly)
By copying these layers into our image separately, we can make Docker cache the large, infrequently changing dependency layers. When you change your application code, only the tiny application layer needs to be rebuilt.
MERN Comparison
This is the direct equivalent of the Node.js best practice where you COPY package.json . and run npm install before you COPY . .. You cache the node_modules layer separately from your application code. Spring Boot's layered JARs provide a standardized way to achieve this for a compiled artifact.
How to Containerize Spring Boot Applications with Docker
Let's revisit the 'How to Containerize Spring Boot Applications with Docker' article to see a practical implementation of this advanced technique.
Read the sections Layered JAR Approach and Layer Caching Strategy. Pay close attention to the three-stage Dockerfile. The second stage (extractor) uses java -Djarmode=layertools to unpack the JAR, and the final stage copies these layers individually.
Your Task (10 minutes): Update to a Layered Dockerfile
Now, let's update our Dockerfile to use this strategy.
-
Enable Layered Jars in
pom.xml: First, you need to tell the Spring Boot Maven plugin to create a layered JAR. Open thepom.xmlinblog-serviceand ensure thespring-boot-maven-pluginconfiguration includes the<layers><enabled>true</enabled></layers>block.<plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <layers> <enabled>true</enabled> </layers> </configuration> </plugin> -
Update
Dockerfile: Replace the content of yourDockerfilewith this new, three-stage version.# --- Stage 1: Build the application --- FROM maven:3.9.6-eclipse-temurin-17 AS builder WORKDIR /app COPY pom.xml . RUN mvn dependency:go-offline -B COPY src ./src RUN mvn clean package -DskipTests # --- Stage 2: Extract the layers from the JAR --- FROM eclipse-temurin:17-jre-alpine AS extractor WORKDIR /app COPY --from=builder /app/target/*.jar app.jar # Use layertools to extract the application into optimized layers RUN java -Djarmode=layertools -jar app.jar extract # --- Stage 3: Create the final runtime image with cached layers --- FROM eclipse-temurin:17-jre-alpine WORKDIR /app RUN addgroup --system appgroup && adduser --system --ingroup appgroup appuser USER appuser # Copy layers in order of change frequency (least to most frequent) COPY --from=extractor /app/dependencies/ ./ COPY --from=extractor /app/spring-boot-loader/ ./ COPY --from=extractor /app/snapshot-dependencies/ ./ COPY --from=extractor /app/application/ ./ EXPOSE 8082 # The entrypoint is now different, as we use the loader that Spring provides ENTRYPOINT ["java", "org.springframework.boot.loader.launch.JarLauncher"]
Debugging Task & Runtime Observation
Let's see the benefit in action.
Your Task (5 minutes):
-
First Build: Build the new layered image:
docker build -t blog-service:0.0.2 .
This will take some time as it's the first build. -
Make a Change: Open any file in
blog-service/src(e.g.,BlogService.java) and add a comment. Don't change any dependencies inpom.xml. -
Second Build: Re-build the image with a new tag:
docker build -t blog-service:0.0.3 .
Observe the build output closely. What do you see?
Click for the answer
You should notice that the second build is dramatically faster. The COPY steps for dependencies, spring-boot-loader, and snapshot-dependencies all show CACHED in the build log. Only the final COPY ... /application/ step is re-executed, followed by the image finalization steps. This proves that we are no longer rebuilding the large dependency layers for simple code changes, saving significant time and storage in a real CI/CD environment.
Conclusion
Excellent work! You have successfully created a production-ready, optimized Docker image for a Spring Boot service. This is a huge step towards building a deployable, scalable system.
Key Takeaways:
- A naive
Dockerfilecreates large, inefficient images by including build tools and source code in the final image. - Multi-stage builds solve this by separating the build environment from the runtime environment, dramatically reducing image size.
- Spring Boot's layered JARs provide a powerful mechanism to optimize Docker's caching, ensuring that only the parts of your application that have changed are rebuilt. This leads to much faster build times.
- Best practices like using a
.dockerignorefile and running as a non-root user are crucial for security and performance.
Preview of the Next Lesson:
Now that you know how to create an optimized Docker image for a single service, it's time to orchestrate our entire multi-service application. In the next lesson, you will create a docker-compose.yml file to build and run the entire application stack—Gateway, Auth Service, Blog Service, and PostgreSQL—with a single command on your local machine.