Optimised Images: Small, Fast, Safe

Optimised Images: Small, Fast, Safe in Java: A naive Java Dockerfile produces a 700 MB image that rebuilds from scratch on every code change and runs as root.

Concept Explanation

A naive Java Dockerfile produces a 700 MB image that rebuilds from scratch on every code change and runs as root. All three are fixable.


The Naive Version

FROM eclipse-temurin:21          # full JDK — ~450 MB
COPY . .
RUN ./mvnw package
CMD ["java", "-jar", "target/app.jar"]

Problems: ships the compiler and your source code to production, re-downloads every dependency on any change, runs as root.


Multi-Stage Build

Build in one image, ship from another. Only the final stage becomes your image:

# ---------- build stage ----------
FROM eclipse-temurin:21-jdk AS build
WORKDIR /app

# Copy dependency descriptors FIRST and resolve them.
# This layer is cached until pom.xml itself changes.
COPY .mvn/ .mvn/
COPY mvnw pom.xml ./
RUN ./mvnw dependency:go-offline -B

# Source changes invalidate only the layers below this line
COPY src/ src/
RUN ./mvnw package -DskipTests -B

# ---------- runtime stage ----------
FROM eclipse-temurin:21-jre-alpine
WORKDIR /app

# Run as a non-root user
RUN addgroup -S spring && adduser -S spring -G spring
USER spring:spring

COPY --from=build /app/target/*.jar app.jar

EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]

The JDK, Maven cache, and source code all stay in the build stage. The shipped image is a JRE plus one jar — roughly 180 MB.


Layer Caching

Docker caches each instruction and invalidates everything after the first change. Copying pom.xml before src/ is the single highest-value optimisation: editing one Java file then reuses the cached dependency layer, turning a three-minute rebuild into fifteen seconds.


Container-Aware JVM Settings

Modern JVMs read container limits, but the default heap is 25% of available memory. Be explicit:

ENTRYPOINT ["java", \
  "-XX:MaxRAMPercentage=75.0", \
  "-XX:+UseContainerSupport", \
  "-jar", "app.jar"]

Never hard-code -Xmx512m — it ignores whatever the orchestrator actually granted.


Health and Configuration

HEALTHCHECK --interval=30s --timeout=3s --start-period=40s \
  CMD wget -qO- http://localhost:8080/actuator/health || exit 1

Configuration arrives as environment variables, which Spring maps automatically:

docker run -e SPRING_PROFILES_ACTIVE=prod \
           -e SPRING_DATASOURCE_PASSWORD="$DB_PASSWORD" \
           -p 8080:8080 my-app:1.4.0

SPRING_DATASOURCE_PASSWORD becomes spring.datasource.password — no config file needed.


Common Mistakes

  1. Secrets baked into the image: Anyone who pulls the image can extract them with docker history. Pass them at runtime.
  2. No .dockerignore: Sending target/, .git/, and node_modules/ to the daemon makes every build slow.
  3. Running as root: A container escape then starts with root privileges.
  4. Tagging everything latest: You lose the ability to say what is running or to roll back.
  5. A JDK in the runtime image: A JRE is enough and much smaller.

Best Practices

  • Multi-stage builds always: Build tools never belong in production images.
  • Dependencies before source for effective layer caching.
  • Non-root user, explicit tag, JRE base image.
  • Add a .dockerignore covering target/, .git/, *.md, and IDE folders.
  • Consider layertools: Spring Boot can split the jar so dependency layers cache separately from your classes.

Practice Exercises

  1. The Size Diff: Build the naive and multi-stage versions of the same app and compare docker images output.
  2. The Cache Hit: Change one line of Java and rebuild. Confirm the dependency layer was reused.
  3. The Runtime Config: Override the server port and active profile using only -e flags, without rebuilding.