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
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.
| Approach | Command | Best for |
|---|---|---|
| Dockerfile with the extracted jar | docker build | Full control over the base image and flags |
| Cloud Native Buildpacks | mvn spring-boot:build-imagegradle bootBuildImage | Good images with no Dockerfile to maintain |
| Jib | Jib Maven or Gradle plugin | Building without a Docker daemon |
| Native image in a container | mvn -Pnative spring-boot:build-image | Fast 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
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"]
runs a tool built into every Spring Boot jar instead of the application.-Djarmode=tools writes one directory per layer, andextract --layers shows which layers a jar has.list-layers- The four
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.COPY - The
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.application.jar - The exec form of
, a JSON array, makesENTRYPOINT the container's main process, so it receives the stop signal directly. The shell form,java , wraps it in a shell that may not pass the signal on.ENTRYPOINT java -jar ...
Two more lines are worth adding in production. USERdocker 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-XX:MaxRAM-XX:ActiveProcessorCount
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");
}
}
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.
raised the heap to about 736 MB of the same 1 GB, leaving room for metaspace, thread stacks, direct buffers and the JIT.-XX:MaxRAMPercentage=75- With 1 CPU, the JVM chose the Serial collector (
andCopy ). 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.MarkSweepCompact - At 4 GB the default heap was 1024 MB and the 75% setting gave 3072 MB.
Set -XX:MaxRAMPercentage-XmxJAVA_TOOL_OPTIONS
Stopping cleanly on SIGTERM
Docker, Kubernetes and most platforms stop a container by sending SIGTERMSIGKILLSIGTERM
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");
}
}
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
, the default since Spring Boot 3.4, the request in progress completed withserver.shutdown=graceful after the signal. Tomcat stopped accepting new connections and waited for active requests before the context closed.200 report ready - With
, the same request failed with animmediate on the client: the server closed the connection mid-request.IOException - 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-phaseSIGKILLpreStopOUT_OF_SERVICE
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:
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:
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);
}
}
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
, which makes Spring Boot exit right after the context has been refreshed, so-Dspring.context.exit=onRefresh was never printed. All classes needed for startup were loaded by then, and about 50 MB of cache was written.started, listening - 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
, 94% of the classes came from the cache, including Spring's and Tomcat's, already parsed and linked. The application then started as usual.-XX:AOTCache=app.aot - The cache only works with classes from jar files, which is why the program packs its classes into
first. The extracted layout from the Dockerfile above is made of jars for the same reason.application.jar
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.jarENTRYPOINT ["java", "-XX:AOTCache=app.aot", "-jar", "application.jar"]-XX:ArchiveClassesAtExit=application.jsa-XX:SharedArchiveFile=application.jsa
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:
./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
For local development the other way round, running the services an application needs in containers, Spring Boot's spring-boot-docker-composecompose.yamlspring.datasource.*
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, optionaldevelopmentOnlySPRING_DATASOURCE_URLspring.datasource.url
Choosing how to containerise
| Decision | Recommendation |
|---|---|
| Building the image | Buildpacks for little maintenance; a layered Dockerfile for full control |
| Layer layout | java -Djarmode=tools -jar app.jar extract --layers |
| Base image | A JRE image of the Java version you build with, run as a non-root user |
| Heap size | -XX:MaxRAMPercentage-Xmx |
| Small containers, 1 CPU | Expect the Serial collector, or choose a collector explicitly |
| Stopping | Exec-form ENTRYPOINT |
| Startup time | AOT cache on Java 25, class data sharing on Java 21, or a native image |
| Configuration and secrets | Environment variables and mounted secrets, not files baked into the image |
| Local dependent services | spring-boot-docker-composecompose.yaml |
A good Spring Boot image is layered, sized from its container limits and stops gracefully; everything else is tuning. The