How to Create Dockerfile for Spring Boot Application
To create a
Dockerfile for a Spring Boot application, use a multi-stage build starting with a Java build image to compile your app, then copy the built jar into a lightweight Java runtime image. This approach keeps the final image small and efficient.Syntax
A typical Dockerfile for Spring Boot uses a multi-stage build:
- FROM: specifies the base image for each stage.
- 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 run your 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 runtime. 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 inside the container listening on its configured port.
Common Pitfalls
Common mistakes include:
- Using a single-stage build with a full 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
ENTRYPOINTor using incorrect Java command syntax.
Always use multi-stage builds and verify your jar path.
dockerfile
### Wrong (single stage, large image) FROM eclipse-temurin:17-jdk WORKDIR /app COPY . . RUN ./mvnw clean package -DskipTests ENTRYPOINT ["java", "-jar", "target/*.jar"] ### Right (multi-stage, smaller image) 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"]
Quick Reference
Tips for creating Dockerfile for Spring Boot:
- Use multi-stage builds to keep images small.
- Use JDK image only for building, JRE image for running.
- Copy only the built jar to the runtime image.
- Set
ENTRYPOINTto run the jar withjava -jar. - Skip tests during build for faster image creation if tests are run separately.
Key Takeaways
Use multi-stage Dockerfile to separate build and runtime for smaller images.
Build your Spring Boot jar in a JDK image, then run it in a lightweight JRE image.
Always copy the built jar correctly from the build stage to the runtime stage.
Set ENTRYPOINT to run your app with 'java -jar app.jar' inside the container.
Skipping tests during Docker build speeds up image creation but run tests separately.