Spring Boot & Spring Cloud

Packaging and Deploying Spring Boot 3: Executable Jars, Containers and Native Images

Intermediate8 min readUpdated

You will be able to take a Spring Boot 3 application from source to production: understand the executable jar layout, build a small, cache-friendly container image with a layered Dockerfile or Cloud Native Buildpacks, size the JVM inside a container, configure graceful shutdown for rolling deployments, and decide when a WAR or a GraalVM native image is the right choice.

What you will learn

  • Describe the executable jar produced by the Spring Boot Maven and Gradle plugins and how it starts
  • Build a container image with a layered multi-stage Dockerfile or with the build-image goal and Cloud Native Buildpacks
  • Configure JVM memory and CPU settings for containers and pass configuration in through the environment
  • Enable graceful shutdown and readiness signalling so rolling deployments drop no requests
  • Explain when to deploy a WAR to an external server and when to compile a GraalVM native image

The build is where the promises of a Spring Boot service are kept or broken: whether the artifact that passed the tests is the one that reaches production, whether a one-line change means a full image rebuild, whether a rolling deployment drops requests, and whether the JVM inside a container knows how much memory it actually has. This page follows a Spring Boot 3 application from package to a running container and covers the decisions along the way, including the two alternative packaging models, the WAR and the native image.

The executable jar

./mvnw package (or ./gradlew bootJar) runs the Spring Boot plugin's repackage step, which turns the ordinary jar into a self-contained executable:

app.jar
├── META-INF/MANIFEST.MF          Main-Class: org.springframework.boot.loader.launch.JarLauncher
│                                 Start-Class: com.example.shop.ShopApplication
├── org/springframework/boot/loader/   the launcher classes
├── BOOT-INF/
│   ├── classes/                  your compiled classes and resources
│   ├── lib/                      every runtime dependency as a nested jar
│   ├── classpath.idx             load order of the dependencies
│   └── layers.idx                layer assignment, used for container images

java -jar app.jar starts JarLauncher, which builds a class loader that reads the nested jars in place (they are stored uncompressed for that reason) and then calls the main method of the Start-Class. Nothing is extracted to disk, no application server is needed, and the same file runs on a laptop, a virtual machine or in a container. The pre-repackage jar is kept as app.jar.original in Maven, and it is that plain jar you publish if another module depends on your classes; the executable one cannot be used as a library.

With Maven, the plugin is inherited from spring-boot-starter-parent; a custom parent needs the repackage goal declared explicitly. Gradle's org.springframework.boot plugin provides bootJar and keeps the standard jar task, whose output carries a -plain classifier so the two cannot be confused. build-info in Maven and springBoot { buildInfo() } in Gradle write META-INF/build-info.properties, which the Actuator info endpoint exposes and which is the cleanest way to know exactly what version is running.

Running from the jar in place is fine on a virtual machine behind a process manager. A systemd unit is the usual arrangement:

[Unit]
Description=Shop service
After=network.target

[Service]
User=shop
WorkingDirectory=/opt/shop
ExecStart=/usr/bin/java -XX:MaxRAMPercentage=75 -jar /opt/shop/app.jar
EnvironmentFile=/etc/shop/env
SuccessExitStatus=143
Restart=on-failure

[Install]
WantedBy=multi-user.target

SuccessExitStatus=143 stops systemd from reporting a failure on the exit code the JVM returns after SIGTERM. Configuration comes from /etc/shop/env and from a config/application.yml next to the jar, both outside the artifact.

Containers: the fast-rebuild problem

Copying app.jar into an image works and is wrong in one specific way: the whole jar is one layer, so every code change invalidates the layer that contains 50 MB of unchanged dependencies, and every deploy pushes and pulls all of it. Boot solves this with layered jars. layers.idx assigns the jar's content to layers ordered from least to most likely to change: dependencies, spring-boot-loader, snapshot-dependencies, application. The jar's tools mode extracts them:

java -Djarmode=tools -jar app.jar extract --layers --destination extracted
# Boot 3.2 and earlier: java -Djarmode=layertools -jar app.jar extract

A multi-stage Dockerfile then copies each layer separately, so a code change only rebuilds the last COPY:

# ---- build stage: produce and explode the jar
FROM eclipse-temurin:21-jdk AS build
WORKDIR /workspace
COPY .mvn .mvn
COPY mvnw pom.xml ./
RUN --mount=type=cache,target=/root/.m2 ./mvnw -q dependency:go-offline
COPY src src
RUN --mount=type=cache,target=/root/.m2 ./mvnw -q -DskipTests package \
 && cp target/*.jar app.jar \
 && java -Djarmode=tools -jar app.jar extract --layers --destination extracted

# ---- runtime stage: small JRE, non-root, one COPY per layer
FROM eclipse-temurin:21-jre
RUN useradd --system --uid 1001 app
WORKDIR /app
COPY --from=build --chown=app /workspace/extracted/dependencies/ ./
COPY --from=build --chown=app /workspace/extracted/spring-boot-loader/ ./
COPY --from=build --chown=app /workspace/extracted/snapshot-dependencies/ ./
COPY --from=build --chown=app /workspace/extracted/application/ ./
USER app
EXPOSE 8080
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "app.jar"]

The extract --layers layout places a thin app.jar plus a lib/ directory in each layer, and the launcher reads them from the file system instead of from nested entries, which also starts slightly faster than the fat jar. Because dependencies changes only when pom.xml does, day-to-day builds produce one small new layer.

The Docker fundamentals guide explains multi-stage builds, cache mounts and .dockerignore in general; the Boot-specific points are the layer extraction and the choice of a JRE image (-jre, not -jdk) for the runtime stage.

Buildpacks instead of a Dockerfile

./mvnw spring-boot:build-image (or ./gradlew bootBuildImage) produces an OCI image with no Dockerfile at all, using Cloud Native Buildpacks (the Paketo implementation by default). The buildpack detects a Boot application, selects a JVM, applies the same layering, computes JVM memory flags at container start from the cgroup limit through its memory calculator, runs as a non-root user and records a software bill of materials. Configuration goes through plugin properties or environment variables:

<plugin>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-maven-plugin</artifactId>
  <configuration>
    <image>
      <name>registry.example.com/shop/orders:${project.version}</name>
      <env>
        <BP_JVM_VERSION>21</BP_JVM_VERSION>
        <BPE_APPEND_JAVA_TOOL_OPTIONS>-XX:+ExitOnOutOfMemoryError</BPE_APPEND_JAVA_TOOL_OPTIONS>
      </env>
    </image>
  </configuration>
</plugin>

Buildpacks need a Docker daemon (or a compatible socket such as Podman's) during the build, and the base images are the ones Paketo publishes, which is either a benefit or a blocker depending on your organisation's image policy. When a platform team mandates a hardened base image, the Dockerfile route is the one that fits.

Configuring the JVM in a container

Modern JVMs (Java 17 and 21 included) read the container's cgroup limits and size the default heap accordingly, but the default is a quarter of the limit, which wastes most of a 1 GiB container. Prefer a percentage over a fixed -Xmx so the same image works with different limits:

SettingRecommendation
Heap-XX:MaxRAMPercentage=75 (lower if the app uses a lot of off-heap memory); avoid -Xmx in images
Initial heap-XX:InitialRAMPercentage equal to the max avoids resizing pauses in steady-state services
CPUThe JVM derives its parallelism from the CPU quota; a limit below 2 CPUs makes G1 and the JIT noticeably slower to warm up
Garbage collectorG1 is the default and fine; ZGC or Shenandoah for latency-sensitive services with large heaps; Serial GC for very small containers
Diagnostics-XX:+ExitOnOutOfMemoryError so the orchestrator restarts a dead process instead of leaving a zombie; -XX:+HeapDumpOnOutOfMemoryError to a mounted volume

JAVA_TOOL_OPTIONS is read by every JVM launch and is the conventional environment variable to inject these flags from a Kubernetes manifest without rebuilding the image. Total container memory must exceed the heap by enough for metaspace, thread stacks (each Tomcat thread reserves stack space), the code cache and direct buffers; a container killed with exit code 137 is the kernel enforcing the limit, not a Java OutOfMemoryError.

Boot 3.2 and Java 21 add one setting worth knowing: spring.threads.virtual.enabled=true makes Tomcat and Boot's task executors use virtual threads, which removes the thread-pool ceiling for I/O-bound services without changing code.

Configuration and secrets at runtime

The image must not contain environment-specific values. Feed them in through the mechanisms the configuration guide describes, in this order of preference: environment variables for simple values, mounted files for secrets (spring.config.import=optional:configtree:/run/secrets/), a config server or secret manager for anything shared across many services. A Kubernetes deployment fragment:

env:
  - name: SPRING_PROFILES_ACTIVE
    value: prod
  - name: JAVA_TOOL_OPTIONS
    value: "-XX:MaxRAMPercentage=75 -XX:+ExitOnOutOfMemoryError"
  - name: SPRING_DATASOURCE_PASSWORD
    valueFrom:
      secretKeyRef: { name: orders-db, key: password }
resources:
  requests: { cpu: "500m", memory: "768Mi" }
  limits: { memory: "768Mi" }

Setting the memory request equal to the limit gives the container a guaranteed allocation; a CPU limit is often left off so the JVM can burst during startup and JIT compilation.

Graceful shutdown and rolling deployments

Deploying a new version means stopping old instances while requests are in flight. Two settings make that safe:

server:
  shutdown: graceful
spring:
  lifecycle:
    timeout-per-shutdown-phase: 30s

On SIGTERM, Boot stops accepting new connections, lets active requests finish for up to the timeout, then stops the context. With the Kubernetes readiness probe pointed at /actuator/health/readiness (see the observability guide), the sequence becomes: the pod is marked terminating, readiness flips to refusing traffic, the Service stops routing to it, in-flight requests drain, the process exits. Set the pod's terminationGracePeriodSeconds above the Boot timeout, and consider a short preStop sleep so that load balancers have a moment to notice the readiness change before the process starts shutting down.

Startup matters too: a rolling update that promotes a pod before it can serve traffic causes errors just like an abrupt stop. Use a startup probe or a readiness initialDelaySeconds that reflects the real startup time, which you can read from the startup Actuator endpoint or the log line Boot prints when the application is ready.

Alternatives: WAR files and native images

WAR deployment to an external Tomcat, Jetty or WildFly is still supported for organisations that standardise on an application server. Change the packaging to war, mark spring-boot-starter-tomcat as provided, and extend SpringBootServletInitializer so the server can bootstrap the application without a main method. You lose control over the JVM and server version, gain nothing in performance, and complicate configuration, so choose it only when the operating model requires it.

GraalVM native images compile the application ahead of time into a platform executable. Spring Boot 3 supports this through its ahead-of-time (AOT) engine, which pre-computes the bean definitions and generates the reflection, proxy and resource hints the native compiler needs. With the GraalVM Native Build Tools configured (the native profile in a project generated by Spring Initializr), ./mvnw -Pnative native:compile produces a binary that starts in tens of milliseconds and runs in a fraction of the memory; ./mvnw -Pnative spring-boot:build-image builds it inside a buildpack so no local GraalVM is needed. The price is a slow, memory-hungry build, restrictions on runtime reflection and dynamic proxies (libraries need hints, which Spring provides for its own portfolio and many common dependencies), and a closed-world assumption: profiles and conditions are evaluated at build time, so a native image cannot switch bean sets by activating a profile at runtime. Test the native binary itself in CI; passing JVM tests does not prove the image works.

Between the two extremes, Boot 3.3 introduced a cheaper win: Class Data Sharing (CDS). Extract the jar with -Djarmode=tools, run it once during the image build with -XX:ArchiveClassesAtExit=app.jsa -Dspring.context.exit=onRefresh (the second flag makes Boot exit as soon as the context is ready, so the training run needs no database), and start it in the image with -XX:SharedArchiveFile=app.jsa; startup time typically drops noticeably with no change to how the application behaves.

Common mistakes

Building the image from the fat jar as one layer. Every deploy ships every dependency again. Extract layers or use buildpacks.

Using a JDK image at runtime. The runtime stage needs a JRE; the JDK doubles the image size and adds tools an attacker would appreciate.

Running as root inside the container. A USER instruction or the buildpack's default non-root user costs nothing and limits the damage of a container escape.

Fixed -Xmx baked into the image. The same image then cannot be scheduled with a different memory limit without waste or crashes. Use percentages.

Skipping graceful shutdown. The default is an immediate stop; every rolling update then produces a burst of failed requests that nobody attributes to the deployment.

Configuration files inside the image. An image with application-prod.yml baked in cannot be promoted through environments unchanged and leaks production settings to anyone who can pull it.

Testing native images only on the JVM. Reflection and resource problems appear only in the compiled binary.

Key takeaways

  • The Boot plugin repackages your jar into an executable with nested dependencies; publish the .original jar if the code is also a library.
  • Layered jars extracted with -Djarmode=tools and copied layer by layer, or images produced by build-image with Cloud Native Buildpacks, keep container rebuilds and pushes small.
  • Size the JVM with MaxRAMPercentage and inject flags through JAVA_TOOL_OPTIONS; leave room in the container limit for non-heap memory.
  • Keep environment-specific configuration and secrets out of the image and feed them in through the environment, mounted files or a config server.
  • server.shutdown=graceful plus readiness probes and a suitable termination grace period make rolling deployments lossless.
  • WAR packaging exists for legacy operating models; GraalVM native images trade build time and dynamic behaviour for instant startup and low memory, with CDS as a cheaper middle ground.

Sources and further reading

Frequently asked questions

Why is my Spring Boot jar so much larger than my code?
Because the plugin's repackage step builds a self-contained executable: your classes under BOOT-INF/classes, every runtime dependency under BOOT-INF/lib, and a small launcher that knows how to load jars nested inside a jar. The plain jar produced by the compiler is also kept, with a .original suffix in Maven, and is what you should publish if another project wants to depend on your code as a library.
Should I use a Dockerfile or the build-image goal?
Use build-image (Cloud Native Buildpacks) when you want a well-tuned image without maintaining a Dockerfile: it picks a JVM, sets memory flags, runs as non-root and layers the application automatically. Use a Dockerfile when you need control over the base image, corporate certificates, extra tools or a specific hardening standard. Both can produce layered images that rebuild quickly.
How much memory should I give a Spring Boot container?
Start from the heap the application actually needs under load, then add space for metaspace, thread stacks, code cache and native memory used by the JVM and libraries; a container limit of roughly the heap plus 25 to 50 percent is a common starting point for small services. Let the JVM derive the heap from the limit with MaxRAMPercentage rather than a fixed Xmx, and watch for container restarts caused by the kernel killing a process that exceeded its limit.
Is a GraalVM native image always faster?
It starts in tens of milliseconds and uses far less memory at rest, which matters for serverless functions and dense clusters. Peak throughput is usually somewhat lower than a warmed-up JIT-compiled JVM, builds take minutes and lots of memory, and reflection-heavy libraries need hints. For long-running services with steady traffic the JVM remains the default; choose native when startup time or footprint is the constraint.