Video in progress
How do you build a Docker image for a Spring Boot service so that it is small, quick to update and secure?
I don't copy the fat jar as a single layer: with Boot's layered jar the dependencies go into their own layer, and when the code changes only a small layer is updated. A small JRE base image, a non-root user and a multi-stage build, or Buildpacks, which give you all of that out of the box.
📖 Answer
The problem with a plain COPY target/app.jar: of an 80 MB jar, 79 MB is dependencies and 1 MB is your code. On every commit the whole 80 MB goes up to the registry as a new layer and is pulled to every node.
A multi-stage Dockerfile with a layered jar:
FROM eclipse-temurin:21-jre-alpine AS extract
WORKDIR /app
COPY target/app.jar app.jar
RUN java -Djarmode=tools -jar app.jar extract --layers --launcher --destination extracted
FROM eclipse-temurin:21-jre-alpine
RUN addgroup -S app && adduser -S app -G app
USER app
WORKDIR /app
COPY --from=extract /app/extracted/dependencies/ ./
COPY --from=extract /app/extracted/spring-boot-loader/ ./
COPY --from=extract /app/extracted/snapshot-dependencies/ ./
COPY --from=extract /app/extracted/application/ ./
ENTRYPOINT ["java", "org.springframework.boot.loader.launch.JarLauncher"]
-Djarmode=tools is from Boot 3.3. Before that it was -Djarmode=layertools -jar app.jar extract. And JarLauncher moved to the org.springframework.boot.loader.launch package in Boot 3.2. This is exactly where old Dockerfiles break when you copy them.
Now when the code changes, only the application/ layer (a few hundred KB) is updated.
Another option is to not write a Dockerfile at all: ./mvnw spring-boot:build-image uses Cloud Native Buildpacks to build a layered, non-root image with JVM memory tuned for the container. For many teams this is the path with the fewest mistakes.
A few more habits:
- pin the base image to an exact version and update it regularly, with a CVE scanner in CI (Trivy, Grype);
- don't use the
latesttag in deploys, tag with the commit SHA; - a JRE image, not a JDK; distroless if you can;
- write
ENTRYPOINTin exec form, so SIGTERM goes straight to the Java process and graceful shutdown works.
Sign up to mark studied questions and save your progress.