Running Spring Boot in containers

A Spring Boot image should be layered so that deployments ship only what changed, and the JVM inside it must respect the container's limits and stop cleanly. This page explains the recommended Dockerfile, then runs heap sizing under container limits, graceful shutdown on SIGTERM and a Java 25 AOT cache training run.

Contents

What goes into a Spring Boot container image

A container image is a stack of read-only filesystem layers plus a command to start. For a Spring Boot application, the image holds a Java runtime, the application's dependencies, its own classes, and the java command that starts them. Each layer is stored and downloaded once; when an image is rebuilt, only the layers that changed need to be pushed and pulled again.

That layering decides most of the design. Dependencies change rarely and weigh tens of megabytes, while the application's own classes change on every commit and are small. Copying the whole fat jar as one layer forces every deployment to ship all dependencies again. Spring Boot's build plugins therefore write a layer index into the jar, and Spring Boot can extract the jar into separate directories that map onto image layers.

Ways to build an image for a Spring Boot application
ApproachCommandBest for
Dockerfile with the extracted jardocker buildFull control over the base image and flags
Cloud Native Buildpacksmvn spring-boot:build-image, gradle bootBuildImageGood images with no Dockerfile to maintain
JibJib Maven or Gradle pluginBuilding without a Docker daemon
Native image in a containermvn -Pnative spring-boot:build-imageFast startup and small memory, see the native page

Inside the container, the JVM must also behave well: size its heap from the container's memory limit, stop cleanly when the orchestrator sends a signal, and start fast enough for scaling. The programs on this page run those parts with Spring Boot 4.1.2 on Java 25, simulating container limits with JVM flags and sending real signals to child processes. No Docker daemon is available where this page was built, so the Dockerfiles, Buildpacks and Docker Compose sections show configuration from the Spring Boot reference documentation that was not run here.

A layered Dockerfile

The Spring Boot 4 reference documentation recommends a two-stage Dockerfile. The first stage extracts the fat jar with Spring Boot's tools jar mode; the second copies each extracted layer separately:

Dockerfile
FROM bellsoft/liberica-openjre-debian:25-cds AS builder
WORKDIR /builder
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} application.jar
RUN java -Djarmode=tools -jar application.jar extract --layers --destination extracted

FROM bellsoft/liberica-openjre-debian:25-cds
WORKDIR /application
COPY --from=builder /builder/extracted/dependencies/ ./
COPY --from=builder /builder/extracted/spring-boot-loader/ ./
COPY --from=builder /builder/extracted/snapshot-dependencies/ ./
COPY --from=builder /builder/extracted/application/ ./
ENTRYPOINT ["java", "-jar", "application.jar"]
  • -Djarmode=tools runs a tool built into every Spring Boot jar instead of the application. extract --layers writes one directory per layer, and list-layers shows which layers a jar has.
  • The four COPY lines go from least to most frequently changing: released dependencies, the Spring Boot loader, snapshot dependencies, and the application's own classes and resources. A code change rebuilds only the last layer.
  • The application.jar started at the end is not the fat jar: it contains the application's classes and a manifest whose class path points at the extracted jars. That layout starts faster than a nested fat jar and works with class data sharing and the AOT cache.
  • The exec form of ENTRYPOINT, a JSON array, makes java the container's main process, so it receives the stop signal directly. The shell form, ENTRYPOINT java -jar ..., wraps it in a shell that may not pass the signal on.

Two more lines are worth adding in production. USER with a non-root user limits what a compromised process can do, and a JRE base image without a full JDK keeps the image smaller and its attack surface lower. Build it with docker build --build-arg JAR_FILE=target/myapp.jar -t myapp ..

Heap and CPU limits inside a container

A container's memory limit is enforced by the kernel: a process that exceeds it is killed, with no OutOfMemoryError and no stack trace. Since Java 10 the JVM reads the container's cgroup limits and sizes itself from them. This program simulates two container sizes with -XX:MaxRAM and -XX:ActiveProcessorCount, which act like the limits the JVM would detect:

Java
package docker.memory;

import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class ContainerMemory {

    static void report() {
        long maxHeapMb = Runtime.getRuntime().maxMemory() / 1048576;
        String gc = ManagementFactory.getGarbageCollectorMXBeans().stream()
                .map(GarbageCollectorMXBean::getName).collect(Collectors.joining(", "));
        System.out.println("    max heap about " + Math.round(maxHeapMb / 16.0) * 16
                + " MB, CPUs " + Runtime.getRuntime().availableProcessors() + ", GC: " + gc);
    }

    static void child(String label, String... flags) throws Exception {
        System.out.println(label);
        System.out.flush();
        List<String> command = new ArrayList<>(List.of(
                ProcessHandle.current().info().command().orElseThrow()));
        command.addAll(List.of(flags));
        command.addAll(List.of("-cp", System.getProperty("java.class.path"),
                ContainerMemory.class.getName(), "report"));
        ProcessBuilder builder = new ProcessBuilder(command).inheritIO();
        builder.environment().remove("JAVA_TOOL_OPTIONS");
        builder.start().waitFor();
    }

    public static void main(String[] args) throws Exception {
        if (args.length > 0) {
            report();
            return;
        }
        child("1. A 1 GB, 1 CPU container, JVM defaults:",
                "-XX:MaxRAM=1g", "-XX:ActiveProcessorCount=1");
        child("2. The same container, -XX:MaxRAMPercentage=75:",
                "-XX:MaxRAM=1g", "-XX:ActiveProcessorCount=1", "-XX:MaxRAMPercentage=75");
        child("3. A 4 GB, 2 CPU container, JVM defaults:",
                "-XX:MaxRAM=4g", "-XX:ActiveProcessorCount=2");
        child("4. A 4 GB, 2 CPU container, -XX:MaxRAMPercentage=75:",
                "-XX:MaxRAM=4g", "-XX:ActiveProcessorCount=2", "-XX:MaxRAMPercentage=75");
    }
}
Output
1. A 1 GB, 1 CPU container, JVM defaults:
    max heap about 240 MB, CPUs 1, GC: Copy, MarkSweepCompact
2. The same container, -XX:MaxRAMPercentage=75:
    max heap about 736 MB, CPUs 1, GC: Copy, MarkSweepCompact
3. A 4 GB, 2 CPU container, JVM defaults:
    max heap about 1024 MB, CPUs 2, GC: G1 Young Generation, G1 Concurrent GC, G1 Old Generation
4. A 4 GB, 2 CPU container, -XX:MaxRAMPercentage=75:
    max heap about 3072 MB, CPUs 2, GC: G1 Young Generation, G1 Concurrent GC, G1 Old Generation
  • In a 1 GB container with default settings, the maximum heap was about 240 MB: the JVM takes 25% of the memory limit, and reports slightly less than 256 MB because one survivor space does not count. Three quarters of the container's memory went unused by the heap.
  • -XX:MaxRAMPercentage=75 raised the heap to about 736 MB of the same 1 GB, leaving room for metaspace, thread stacks, direct buffers and the JIT.
  • With 1 CPU, the JVM chose the Serial collector (Copy and MarkSweepCompact). With 2 CPUs and 4 GB it chose G1, its default for larger machines. Small containers get a different garbage collector unless you choose one with a flag.
  • At 4 GB the default heap was 1024 MB and the 75% setting gave 3072 MB.

Set -XX:MaxRAMPercentage rather than a fixed -Xmx, so that the heap follows the limit when the container is resized. Between 50 and 75 percent suits most Spring Boot services; the rest is needed outside the heap, and a heap that fills the whole limit gets the container killed. Pass the flags through JAVA_TOOL_OPTIONS, which the JVM reads from the environment, so they can change without rebuilding the image.

Stopping cleanly on SIGTERM

Docker, Kubernetes and most platforms stop a container by sending SIGTERM, waiting a grace period, and then sending SIGKILL. Whether requests in progress survive depends on the application. This program starts a web application in a child JVM, starts a request that takes 1.5 seconds, and sends SIGTERM halfway through:

Java
package docker.shutdown;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class GracefulShutdown {

    @GetMapping("/report")
    String report() throws InterruptedException {
        Thread.sleep(1500);
        return "report ready";
    }

    /** The application: prints its port, then serves until the process is stopped. */
    static void serve(String shutdownMode) {
        SpringApplication app = new SpringApplication(GracefulShutdown.class);
        app.setDefaultProperties(Map.of(
                "server.port", "0",
                "server.shutdown", shutdownMode,
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN"));
        var context = app.run();
        Runtime.getRuntime().addShutdownHook(new Thread(
                () -> System.out.println("child: shutdown hook started (SIGTERM received)")));
        System.out.println("PORT " + ((WebServerApplicationContext) context)
                .getWebServer().getPort());
    }

    static void stopDuringRequest(String shutdownMode) throws Exception {
        System.out.println("server.shutdown=" + shutdownMode + ":");
        ProcessBuilder builder = new ProcessBuilder(
                ProcessHandle.current().info().command().orElseThrow(),
                "-cp", System.getProperty("java.class.path"),
                GracefulShutdown.class.getName(), shutdownMode).redirectErrorStream(true);
        builder.environment().remove("JAVA_TOOL_OPTIONS");
        Process child = builder.start();
        BufferedReader out = new BufferedReader(new InputStreamReader(child.getInputStream()));
        String line = out.readLine();
        while (!line.startsWith("PORT ")) {
            line = out.readLine();
        }
        int port = Integer.parseInt(line.substring("PORT ".length()));

        CompletableFuture<HttpResponse<String>> inFlight = HttpClient.newHttpClient().sendAsync(
                HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/report")).build(),
                HttpResponse.BodyHandlers.ofString());
        Thread.sleep(500);
        System.out.println("  parent: sending SIGTERM while GET /report is running");
        child.toHandle().destroy();

        try {
            HttpResponse<String> response = inFlight.join();
            System.out.println("  parent: response " + response.statusCode() + " "
                    + response.body());
        } catch (RuntimeException e) {
            System.out.println("  parent: request failed with "
                    + e.getCause().getClass().getSimpleName());
        }
        int exit = child.waitFor();
        List<String> childLines = out.lines().filter(l -> l.startsWith("child")).toList();
        childLines.forEach(l -> System.out.println("  " + l));
        System.out.println("  child exit code " + exit + " (128 + 15 = stopped by SIGTERM)");
    }

    public static void main(String[] args) throws Exception {
        if (args.length > 0) {
            serve(args[0]);
            return;
        }
        stopDuringRequest("graceful");
        stopDuringRequest("immediate");
    }
}
Output
server.shutdown=graceful:
  parent: sending SIGTERM while GET /report is running
  parent: response 200 report ready
  child: shutdown hook started (SIGTERM received)
  child exit code 143 (128 + 15 = stopped by SIGTERM)
server.shutdown=immediate:
  parent: sending SIGTERM while GET /report is running
  parent: request failed with IOException
  child: shutdown hook started (SIGTERM received)
  child exit code 143 (128 + 15 = stopped by SIGTERM)
  • With server.shutdown=graceful, the default since Spring Boot 3.4, the request in progress completed with 200 report ready after the signal. Tomcat stopped accepting new connections and waited for active requests before the context closed.
  • With immediate, the same request failed with an IOException on the client: the server closed the connection mid-request.
  • In both runs the JVM ran its shutdown hooks, which is where Spring Boot closes the application context, and exited with code 143, the conventional 128 plus signal number 15.

The graceful phase waits at most spring.lifecycle.timeout-per-shutdown-phase, 30 seconds by default, which should be shorter than the platform's grace period: Kubernetes also waits 30 seconds by default before SIGKILL. A load balancer may still send new requests for a moment after the signal, so Kubernetes deployments often add a short preStop sleep. The readiness probe from the Actuator page reports OUT_OF_SERVICE once shutdown starts, which tells the platform to stop routing traffic.

Faster startup with the AOT cache

A JVM spends much of its startup reading, parsing and linking classes, several thousand of them for a Spring Boot web application. Java 24 added an ahead-of-time cache (JEP 483) that stores classes already loaded and linked, and Java 25 simplified creating it (JEP 514) and added method profiles (JEP 515). The cache is created by a training run. This small web application is the program being started:

Java
package docker.app;

import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class DemoApp {

    @GetMapping("/hello")
    String hello() {
        return "hello from a container-ready app";
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(DemoApp.class);
        app.setDefaultProperties(Map.of(
                "server.port", "0",
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN"));
        var context = app.run(args);
        int port = ((WebServerApplicationContext) context).getWebServer().getPort();
        System.out.println("    started, listening: " + (port > 0));
        context.close();
    }
}

The next program packs it into a jar, runs the training run that the documentation's Dockerfile uses, and then starts it with and without the cache, counting where each class came from:

Java
package docker.cache;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.stream.Stream;

public class AotCacheTraining {

    static final String JAVA = ProcessHandle.current().info().command().orElseThrow();

    /** Packs the compiled docker.app classes into a jar: the AOT cache only covers jars. */
    static Path packApplicationJar(Path dir) throws IOException {
        Path classes = Path.of(AotCacheTraining.class.getProtectionDomain()
                .getCodeSource().getLocation().getPath());
        Path jar = dir.resolve("application.jar");
        try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jar));
                Stream<Path> files = Files.walk(classes.resolve("docker/app"))) {
            for (Path file : files.filter(Files::isRegularFile).toList()) {
                out.putNextEntry(new JarEntry(classes.relativize(file).toString()));
                Files.copy(file, out);
                out.closeEntry();
            }
        }
        return jar;
    }

    static List<String> run(List<String> jvmFlags, String classpath) throws Exception {
        List<String> command = new ArrayList<>(List.of(JAVA));
        command.addAll(jvmFlags);
        command.addAll(List.of("-cp", classpath, "docker.app.DemoApp"));
        ProcessBuilder builder = new ProcessBuilder(command).redirectErrorStream(true);
        builder.environment().remove("JAVA_TOOL_OPTIONS");
        Process process = builder.start();
        List<String> lines = new String(process.getInputStream().readAllBytes()).lines().toList();
        System.out.println("    exit code " + process.waitFor());
        return lines;
    }

    static long countLoaded(List<String> log, String source) {
        return log.stream().filter(l -> l.contains("source: " + source)).count();
    }

    public static void main(String[] args) throws Exception {
        Path dir = Files.createTempDirectory("aotcache");
        Path appJar = packApplicationJar(dir);
        String dependencies = Stream.of(System.getProperty("java.class.path")
                .split(File.pathSeparator)).filter(p -> p.endsWith(".jar"))
                .reduce((a, b) -> a + File.pathSeparator + b).orElseThrow();
        String classpath = appJar + File.pathSeparator + dependencies;
        Path cache = dir.resolve("app.aot");

        System.out.println("Java " + Runtime.version().feature());
        System.out.println("1. Training run, -XX:AOTCacheOutput=app.aot"
                + " -Dspring.context.exit=onRefresh:");
        List<String> training = run(List.of("-XX:AOTCacheOutput=" + cache,
                "-Dspring.context.exit=onRefresh"), classpath);
        training.stream().filter(l -> l.startsWith("    ")).forEach(System.out::println);
        System.out.println("    cache written: " + Files.exists(cache) + ", size about "
                + Math.round(Files.size(cache) / 1048576.0 / 10) * 10 + " MB");

        System.out.println("2. Normal start:");
        List<String> normal = run(List.of("-Xlog:class+load=info"), classpath);
        long normalTotal = normal.stream().filter(l -> l.contains("source: ")).count();
        System.out.println("    classes loaded: about " + Math.round(normalTotal / 100.0) * 100
                + ", from the CDS archive of the JDK: "
                + countLoaded(normal, "shared objects file") * 100 / normalTotal + "%");

        System.out.println("3. Start with -XX:AOTCache=app.aot:");
        List<String> cached = run(List.of("-XX:AOTCache=" + cache, "-Xlog:class+load=info"),
                classpath);
        long fromCache = countLoaded(cached, "shared objects file");
        long total = cached.stream().filter(l -> l.contains("source: ")).count();
        System.out.println("    classes loaded: about " + Math.round(total / 100.0) * 100
                + ", from the AOT cache: " + fromCache * 100 / total + "%");
        cached.stream().filter(l -> l.startsWith("    ")).forEach(System.out::println);
    }
}
Output
Java 25
1. Training run, -XX:AOTCacheOutput=app.aot -Dspring.context.exit=onRefresh:
    exit code 0
    cache written: true, size about 50 MB
2. Normal start:
    exit code 0
    classes loaded: about 7100, from the CDS archive of the JDK: 19%
3. Start with -XX:AOTCache=app.aot:
    exit code 0
    classes loaded: about 7400, from the AOT cache: 94%
    started, listening: true
  • The training run used -Dspring.context.exit=onRefresh, which makes Spring Boot exit right after the context has been refreshed, so started, listening was never printed. All classes needed for startup were loaded by then, and about 50 MB of cache was written.
  • A normal start loaded about 7100 classes, and only 19% came from the JDK's own class data sharing archive, which covers JDK classes only.
  • With -XX:AOTCache=app.aot, 94% of the classes came from the cache, including Spring's and Tomcat's, already parsed and linked. The application then started as usual.
  • The cache only works with classes from jar files, which is why the program packs its classes into application.jar first. The extracted layout from the Dockerfile above is made of jars for the same reason.

The cache must be created with the same JVM version and the same class path as the runs that use it; the JVM rejects a mismatched cache and starts normally. That is why the documentation's Dockerfile performs the training run inside the image build: RUN java -XX:AOTCacheOutput=app.aot -Dspring.context.exit=onRefresh -jar application.jar, then ENTRYPOINT ["java", "-XX:AOTCache=app.aot", "-jar", "application.jar"]. On Java 21 the older equivalent is class data sharing, with -XX:ArchiveClassesAtExit=application.jsa for the training run and -XX:SharedArchiveFile=application.jsa to use it. The startup time saved was not measured here, because the build machine was shared and timings were not repeatable.

Buildpacks and Docker Compose

Buildpacks build an image without a Dockerfile. The Spring Boot plugins run the Paketo buildpacks in a builder container, which picks a JRE, extracts the layers, adds a memory calculator that sets the heap flags from the container limit, and runs as a non-root user:

Shell
./mvnw spring-boot:build-image -Dspring-boot.build-image.imageName=myorg/shop:1.4.2
./gradlew bootBuildImage --imageName=myorg/shop:1.4.2

Builder settings, environment variables such as BP_JVM_VERSION, and the image name can also be set in the plugin configuration. Buildpacks need a Docker-compatible daemon, but no Dockerfile.

For local development the other way round, running the services an application needs in containers, Spring Boot's spring-boot-docker-compose module reads a compose.yaml in the project, starts the containers when the application starts, and creates the connection details for them. With this file, a JDBC application connects to PostgreSQL without any spring.datasource.* properties:

YAML
services:
  postgres:
    image: postgres:17
    environment:
      POSTGRES_DB: shop
      POSTGRES_USER: shop
      POSTGRES_PASSWORD: secret
    ports:
      - "5432"

The module is meant for development: it is skipped in tests by default and should be declared as a development-only dependency, optional in Maven or developmentOnly in Gradle. In production, pass connection settings as environment variables, as the configuration properties page shows; SPRING_DATASOURCE_URL in a container maps to spring.datasource.url. None of the commands in this section were run here.

Choosing how to containerise

Container decisions for a Spring Boot application
DecisionRecommendation
Building the imageBuildpacks for little maintenance; a layered Dockerfile for full control
Layer layoutjava -Djarmode=tools -jar app.jar extract --layers, application layer last
Base imageA JRE image of the Java version you build with, run as a non-root user
Heap size-XX:MaxRAMPercentage between 50 and 75, not a fixed -Xmx
Small containers, 1 CPUExpect the Serial collector, or choose a collector explicitly
StoppingExec-form ENTRYPOINT, graceful shutdown, a phase timeout shorter than the grace period
Startup timeAOT cache on Java 25, class data sharing on Java 21, or a native image
Configuration and secretsEnvironment variables and mounted secrets, not files baked into the image
Local dependent servicesspring-boot-docker-compose with a compose.yaml

A good Spring Boot image is layered, sized from its container limits and stops gracefully; everything else is tuning. The native image page covers the GraalVM route, the CRaC page covers checkpoint and restore, and the Actuator page explains the health probes that orchestrators call.