Skip to content
Tutorials Center
My learning

Topics

Lesson 55 of 66 ยท Packaging and Deployment

Containers: Dockerfile and Buildpacks

Package a Spring Boot app as a container image: layered Dockerfile, bootBuildImage buildpacks, non-root user, memory settings, health probes and image size.

Almost every Spring Boot service ends up in a container. A container image bundles the JVM, your jar and its configuration into one artifact that runs the same on a laptop, in CI and in a cluster. Spring Boot gives you two good ways to build that image: a hand-written Dockerfile, and Cloud Native Buildpacks, which build the image for you without a Dockerfile.

This lesson shows both, then the settings that matter most in production: running as a non-root user, giving the JVM the right amount of memory, wiring health probes, and keeping the image small. If Docker itself is new to you, start with Docker, and for the Java-specific view see Docker for Java and Docker recipe: Java. It builds on Building and Running the Jar.

The Docker daemon and the build tools cannot run on this site, so every command and file below is read-only. The two runnable examples are stand-ins that model the ideas: how layers are split, and how heap size is calculated inside a memory limit.

The naive Dockerfile and why it is slow

The shortest possible Dockerfile copies the fat jar and runs it:

DOCKERFILE
FROM eclipse-temurin:25-jre
COPY target/shop.jar /app/shop.jar
ENTRYPOINT ["java", "-jar", "/app/shop.jar"]

It works, but the jar is one 60 MB layer. Change a single line of your code and Docker has to rebuild, push and pull that whole layer again, even though 59 MB of it is third-party libraries that did not change. Over hundreds of builds that wastes time and registry storage.

The fix is to split the jar into layers ordered from "changes rarely" to "changes often". Spring Boot's jar already records such a split in a file named layers.idx.

Four layers in a Boot jar

dependencies Released libraries. Change on upgrades only.
spring-boot-loader The launcher classes. Almost never change.
snapshot-dependencies Libraries marked SNAPSHOT. Change often.
application Your classes and resources. Change every commit.

Docker caches each layer separately, so only the last ones are rebuilt.

1 / 2

A layered, multi-stage Dockerfile

Since Spring Boot 3.3 the jar can extract itself into those layers with a built-in tool (-Djarmode=tools). A multi-stage build does the extraction in the first stage and copies only the result into a small runtime image:

DOCKERFILE
# ---- stage 1: split the jar into layers ----
FROM eclipse-temurin:25-jre AS extract
WORKDIR /build
COPY target/shop.jar shop.jar
RUN java -Djarmode=tools -jar shop.jar extract --layers --destination extracted

# ---- stage 2: the runtime image ----
FROM eclipse-temurin:25-jre
RUN groupadd --system --gid 10001 spring \
 && useradd  --system --uid 10001 --gid spring --no-create-home spring
WORKDIR /app

# least likely to change first, most likely to change last
COPY --from=extract /build/extracted/dependencies/          ./
COPY --from=extract /build/extracted/spring-boot-loader/    ./
COPY --from=extract /build/extracted/snapshot-dependencies/ ./
COPY --from=extract /build/extracted/application/           ./

USER 10001
EXPOSE 8080
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "shop.jar"]

Three details deserve attention:

  • Order of COPY lines. Docker reuses a cached layer only if everything above it is unchanged, so the stable layers go first. This is the same idea as in Build cache.
  • Exec form of ENTRYPOINT. The JSON array makes the JVM process number 1 in the container, so it receives SIGTERM directly and can shut down gracefully. A shell-form ENTRYPOINT java -jar ... puts a shell in front and the signal may never reach Java.
  • USER 10001. More on that in a moment.

A .dockerignore file that excludes everything except the jar keeps the build context small and stops local files, such as .env, from sneaking into an image.

Run the next example to see why the split pays off. It builds a model of the jar twice, with a different change each time, and shows which layers get a new digest and so must be pushed again.

Java Which layers change when you rebuild?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

A code change rebuilds only the tiny application layer. A dependency upgrade rebuilds the big one, but that happens rarely. The real tool uses the layers.idx file inside the jar, and Docker compares layer contents rather than this toy digest, but the effect is the same.

Buildpacks: an image without a Dockerfile

Cloud Native Buildpacks inspect your project, pick a suitable JVM and base image, and produce a layered image automatically. Spring Boot's build plugins call them for you, using the Paketo Java buildpacks:

Terminal
# Maven
./mvnw spring-boot:build-image

# Gradle
./gradlew bootBuildImage --imageName=registry.example.com/shop/api:1.0.0

You still need a running Docker daemon, because the build happens inside containers. Settings go into the build file:

XML
<plugin>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-maven-plugin</artifactId>
  <configuration>
    <image>
      <name>registry.example.com/shop/api:${project.version}</name>
      <env>
        <BP_JVM_VERSION>25</BP_JVM_VERSION>
      </env>
    </image>
  </configuration>
</plugin>
Kotlin
tasks.named<org.springframework.boot.gradle.tasks.bundling.BootBuildImage>("bootBuildImage") {
    imageName.set("registry.example.com/shop/api:${project.version}")
    environment.put("BP_JVM_VERSION", "25")
}
Hand-written Dockerfile Buildpacks
Control Total: any base image, any step Limited to buildpack options
Maintenance You patch the base image yourself Rebuild with a newer builder to pick up OS and JVM patches
Layering You write it Automatic
Memory settings You choose flags Calculated at container start
Extra tools in the image Whatever you add Minimal, runs as a non-root user by default
Needs Dockerfile skills Yes No

Neither is "better". Buildpacks suit teams that want a consistent, patched image with little effort. A Dockerfile suits teams that need a special base image, extra system packages or exact control.

Never run as root

A process running as root inside a container is one kernel bug away from being root on the host, and it can write anywhere in the image. Always add USER with a numeric id, as in the Dockerfile above, and make sure the application only writes to directories it owns, such as a mounted volume or /tmp. Buildpack images already run as a non-root user. For more background see Non-root users and capabilities.

Memory: the JVM must know its limit

Modern JVMs read the container's memory limit, but the default heap is only a quarter of it. Two common ways to set it:

  • -XX:MaxRAMPercentage=75 gives the heap a fixed share of the limit.
  • The buildpack memory calculator works out the heap at start-up from the limit, the number of loaded classes and an assumed thread count. Tune it with BPL_JVM_THREAD_COUNT or override everything with JAVA_TOOL_OPTIONS.

The heap is not the whole JVM. Metaspace, the code cache, thread stacks and direct buffers sit on top of it. If the heap takes 75% of a small container, the rest may not fit and the kernel kills the process with an out-of-memory error. The model below uses illustrative sizes to show the difference.

Java Heap size inside a container limit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

On a 512 MB container the flat 75% rule overshoots, while the calculator approach leaves room for everything else. In practice, give a Spring Boot service at least 512 MB to 1 GB, measure with the Actuator metrics, and set the limit above heap + non-heap. See also Resource limits.

Health probes and graceful stop

An orchestrator needs to know whether a container is alive and whether it is ready for traffic. Spring Boot's Actuator provides both as separate endpoints:

YAML
management:
  endpoint:
    health:
      probes:
        enabled: true
server:
  shutdown: graceful

/actuator/health/liveness answers "should this container be restarted?" and /actuator/health/readiness answers "should it receive requests right now?". Boot enables them automatically when it detects Kubernetes. A Docker HEALTHCHECK is optional: many runtime images do not include curl, and Kubernetes ignores it and uses its own probes. With server.shutdown=graceful, a SIGTERM makes the server finish in-flight requests before the JVM exits. The next lessons put those probes to work, and Docker healthchecks covers the Docker side.

Docker Compose for Boot with MySQL and Kafka

A real application rarely runs alone. To start the app and its MySQL database and a Kafka broker with one command, describe all three in a compose.yaml (the Compose basics are in Docker Compose):

YAML
services:
  app:
    image: shop-app:latest
    ports:
      - "8080:8080"
    environment:
      SPRING_DATASOURCE_URL: jdbc:mysql://mysql:3306/shop
      SPRING_DATASOURCE_USERNAME: shop
      SPRING_DATASOURCE_PASSWORD: ${DB_PASSWORD}
      SPRING_KAFKA_BOOTSTRAP_SERVERS: kafka:9092
    depends_on:
      mysql:
        condition: service_healthy
      kafka:
        condition: service_healthy
    networks:
      - backend

  mysql:
    image: mysql:8.4
    environment:
      MYSQL_DATABASE: shop
      MYSQL_USER: shop
      MYSQL_PASSWORD: ${DB_PASSWORD}
      MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD}
    volumes:
      - mysql-data:/var/lib/mysql
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-p${DB_ROOT_PASSWORD}"]
      interval: 5s
      timeout: 3s
      retries: 20
      start_period: 20s
    networks:
      - backend

  kafka:
    image: apache/kafka:4.0.0
    ports:
      - "9094:9094"          # for tools running on your own machine
    environment:
      KAFKA_NODE_ID: 1
      KAFKA_PROCESS_ROLES: broker,controller
      KAFKA_LISTENERS: INTERNAL://:9092,CONTROLLER://:9093,EXTERNAL://:9094
      KAFKA_ADVERTISED_LISTENERS: INTERNAL://kafka:9092,EXTERNAL://localhost:9094
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INTERNAL:PLAINTEXT,CONTROLLER:PLAINTEXT,EXTERNAL:PLAINTEXT
      KAFKA_INTER_BROKER_LISTENER_NAME: INTERNAL
      KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER
      KAFKA_CONTROLLER_QUORUM_VOTERS: 1@kafka:9093
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
      KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
    healthcheck:
      test: ["CMD-SHELL", "/opt/kafka/bin/kafka-broker-api-versions.sh --bootstrap-server kafka:9092 > /dev/null 2>&1"]
      interval: 10s
      timeout: 10s
      retries: 12
      start_period: 20s
    networks:
      - backend

networks:
  backend:

volumes:
  mysql-data:

The file has passed docker compose config (syntax and variable checks); starting the full stack needs the images and a few minutes on your machine. The parts worth understanding:

  • Service names are host names. On the shared backend network the app reaches MySQL at mysql:3306 and Kafka at kafka:9092. localhost inside the app container means the container itself, which is the most common Compose mistake. See Compose networks.
  • Configuration through the environment. SPRING_DATASOURCE_URL and SPRING_KAFKA_BOOTSTRAP_SERVERS override the matching properties through Boot's relaxed binding (Properties and YAML), so the same image runs in every environment. Passwords come from ${DB_PASSWORD}, filled from your shell or an untracked .env file, never from the file in Git.
  • Health checks plus depends_on conditions. A plain depends_on: [mysql] only waits until the container has started, and MySQL needs many more seconds before it accepts connections. condition: service_healthy makes Compose wait for the health check to pass. See Compose depends_on and health. Even so, keep your app resilient: connection pools and Kafka clients retry, and a restart policy covers the rest.
  • Two Kafka listeners. Kafka tells clients which address to use for follow-up connections (the advertised listener). Containers must use kafka:9092; a tool on your own computer must use localhost:9094. A single listener cannot serve both, so the broker has an internal and an external one.
  • A named volume (mysql-data) keeps the database when the container is recreated. docker compose down -v deletes it.
  • Schema setup belongs to the app: let Flyway or Liquibase create tables at startup, and let Kafka topics be created by NewTopic beans (Kafka in Practice).

Spring Boot can also manage Compose for you during development. Add spring-boot-docker-compose and a compose.yaml in the project root: when you run the application from your IDE, Boot starts the services, detects the connection details (host, mapped port, credentials) for known images such as MySQL and Kafka, and stops them again on exit. You then need no datasource URL in application.properties for local work. Use the full Compose file above to run the packaged application together with its dependencies.

The start-up order, simulated

The stand-in resolves a depends_on graph with health checks: each service becomes healthy a fixed number of seconds after it starts, and a service starts only when every dependency is healthy. It shows why the order matters and how long the whole stack takes. What is real: the rule that service_healthy waits for the check to pass. What is the stand-in: the time units are made up.

Java Start order with health-gated dependencies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

MySQL and Kafka start in parallel because neither depends on the other, so the app waits only for the slower one. Without health conditions the app would start at t=0 and crash while its dependencies were still booting.

Keeping the image small

  • JRE, not JDK. The runtime image needs only a JRE. The JDK adds compilers and tools you do not run in production.
  • Layers over fat jars, as above, so each push moves only what changed.
  • Slim bases. Distroless or minimal images drop the shell and package manager, which shrinks both size and attack surface, but make debugging harder. Alpine uses musl instead of glibc, so test your app on it before relying on it. See Choosing base images.
  • A custom runtime with jlink keeps only the Java modules your app needs.
  • A native image (next lesson) can be a fraction of the size, with trade-offs.

A typical image for a web service with JPA lands between 200 MB and 350 MB; a custom runtime or native image can go well below that.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does a layered Dockerfile rebuild faster than copying the fat jar as one layer?

    Docker reuses a cached layer only when it and everything above it are unchanged. Putting stable libraries first and your classes last means a code change invalidates only the last, small layer.
  2. 2. Why should the ENTRYPOINT use the exec (JSON array) form?

    In shell form a shell wraps the java process and may not forward signals, so the application can be killed without a graceful shutdown. The exec form runs java directly.
  3. 3. Which command builds an image with buildpacks and no Dockerfile?

    The Spring Boot Maven plugin goal build-image (and bootBuildImage in Gradle) calls Cloud Native Buildpacks. It needs a running Docker daemon.
  4. 4. A 512 MB container sets -XX:MaxRAMPercentage=75 and gets killed for running out of memory, although the heap never fills up. What is the most likely cause?

    The container limit covers the whole process. Heap plus metaspace, code cache, thread stacks and buffers can exceed it even when the heap itself has free space.

Summary

  • Split the fat jar into layers (-Djarmode=tools ... extract --layers) and copy them from least to most changing, so a code change rebuilds only the small application layer.
  • Use a multi-stage build, a JRE base image, an exec-form ENTRYPOINT and a numeric non-root USER.
  • Buildpacks (spring-boot:build-image, bootBuildImage) create a layered, patched, non-root image without a Dockerfile; they need a Docker daemon.
  • The memory limit covers heap plus non-heap memory: leave room, and measure instead of guessing.
  • Expose liveness and readiness probes with Actuator and enable graceful shutdown.
  • Keep images small with a JRE, slim bases, layers, jlink or a native image.

Next: Native Images with GraalVM.