How to Create Dockerfile for Spring Boot Application
To create a
Dockerfile for a Spring Boot app, use a multi-stage build that first compiles your app with a JDK image, then runs it with a lightweight JRE image. This keeps the final image small and efficient by copying only the built jar file into the runtime image.Syntax
A typical Dockerfile for Spring Boot uses a multi-stage build:
- FROM: specifies the base image (JDK for build, JRE for runtime)
- WORKDIR: sets the working directory inside the container
- COPY: copies files from your project into the container
- RUN: runs commands like building the jar
- ENTRYPOINT: defines the command to start your Spring Boot app
dockerfile
FROM eclipse-temurin:17-jdk AS build WORKDIR /app COPY . . RUN ./mvnw clean package -DskipTests FROM eclipse-temurin:17-jre WORKDIR /app COPY --from=build /app/target/*.jar app.jar ENTRYPOINT ["java", "-jar", "app.jar"]
Example
This example Dockerfile builds a Spring Boot app using Maven and runs it with Java 17 JRE. It first compiles the app in the build stage, then copies the jar to a smaller runtime image.
dockerfile
FROM eclipse-temurin:17-jdk AS build WORKDIR /app COPY . . RUN ./mvnw clean package -DskipTests FROM eclipse-temurin:17-jre WORKDIR /app COPY --from=build /app/target/*.jar app.jar ENTRYPOINT ["java", "-jar", "app.jar"]
Output
When you build and run this Dockerfile, your Spring Boot app starts and listens on its configured port (usually 8080).
Common Pitfalls
Common mistakes include:
- Using only a JDK image for runtime, which makes the image unnecessarily large.
- Not copying the built jar correctly, causing the container to fail at startup.
- Forgetting to set the working directory, leading to file not found errors.
- Not skipping tests during build in Docker, which slows down image creation.
dockerfile
FROM eclipse-temurin:17-jdk WORKDIR /app COPY . . RUN ./mvnw clean package ENTRYPOINT ["java", "-jar", "target/app.jar"] # This creates a large image because it includes the JDK and source files. # Correct approach uses multi-stage build as shown in previous sections.
Quick Reference
Tips for creating Dockerfiles for Spring Boot:
- Use multi-stage builds to keep images small.
- Use official Eclipse Temurin images for Java 17 or newer.
- Set
WORKDIRto organize files inside the container. - Skip tests during Docker build to speed up image creation.
- Expose ports in Docker run command, not necessarily in Dockerfile.
Key Takeaways
Use multi-stage Dockerfile to separate build and runtime for smaller images.
Build your Spring Boot jar with JDK image, then run it with a lightweight JRE image.
Set working directory and copy files carefully to avoid runtime errors.
Skip tests during Docker build to speed up image creation.
Use official Java base images like Eclipse Temurin for best compatibility.