Optimizing Spring Boot Docker Image Layering to Reduce Build Size and Push Overhead
This article explains how to analyze and optimize Spring Boot Docker images by using the new layer‑building feature in Spring Boot 2.3, restructuring Dockerfiles, and employing multi‑stage builds to eliminate duplicate layers, dramatically shrink image size, and speed up image pushes.
In containerized deployments, building Spring Boot images with a base Java image and adding the JAR often leads to large image sizes and increased bandwidth when pushing to a registry; the author investigates this problem and adopts Spring Boot 2.3's layer‑building capability.
Traditional single‑JAR Dockerfile shows a basic Dockerfile that copies the JAR and entrypoint, resulting in a 622 MB base image plus additional layers, with duplicate layers caused by a RUN ln -s /app/logs /app/log && chown 1001.1001 -R /app command.
Inspecting the base image reveals three main layers (CentOS 7, yum install, JDK) and a total size of 622 MB. The build history shows that the RUN ln -s … step creates two identical layers, inflating the final image to about 757 MB.
Optimized Dockerfile creates the log directory and sets permissions before copying the JAR, using COPY --chown=1001:1001 to set ownership, which reduces the image to a single copy layer for the JAR.
Using Spring Boot's layer extraction ( java -Djarmode=layertools -jar xxx.jar extract ) in a multi‑stage build splits the application into dependencies , spring-boot-loader , snapshot-dependencies , and application directories, allowing each to be copied as separate layers.
The final multi‑stage Dockerfile builds a lightweight image where only the application layer changes between versions, resulting in a push of just ~300 KB for a new version instead of the full 757 MB.
Verification steps run the container with appropriate JVM options, confirming successful startup and showing that only the application layer's hash changed (from 248 KB to 253 KB) when the JAR was updated.
The author concludes that understanding Docker's layer caching and Spring Boot's layer‑building feature can dramatically improve build efficiency and reduce network overhead for Java backend services.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.