Packaging and deployment
One artifact, promoted unchanged from dev to production, configured entirely by its environment. Everything in this chapter serves that single rule.
The executable jar
./mvnw clean package java -jar target/bookstore-0.0.1-SNAPSHOT.jar # inspect what is inside jar tf target/bookstore-0.0.1-SNAPSHOT.jar | head -20
BOOT-INF/classes/ ← your compiled code and resources BOOT-INF/lib/ ← every dependency jar, unmodified META-INF/MANIFEST.MF ← Main-Class: JarLauncher, Start-Class: BookstoreApplication org/springframework/boot/loader/ ← the launcher that can read nested jars
The JVM cannot load classes from a jar inside a jar, so Boot ships its own classloader.
JarLauncher starts first, sets that up, then calls your main.
Container images
./mvnw spring-boot:build-image \ -Dspring-boot.build-image.imageName=ghcr.io/bitsnippets/bookstore:1.4.0 docker run -p 8080:8080 -e SPRING_PROFILES_ACTIVE=prod \ ghcr.io/bitsnippets/bookstore:1.4.0
Cloud Native Buildpacks produce an optimised, layered image with a sensible JRE, a non-root user and memory calculation already configured. No Dockerfile to maintain and no base image to patch yourself.
# ---------- build ---------- FROM eclipse-temurin:21-jdk-alpine AS build WORKDIR /build # dependency layer first — cached unless the pom changes COPY .mvn/ .mvn/ COPY mvnw pom.xml ./ RUN ./mvnw dependency:go-offline -B COPY src/ src/ RUN ./mvnw clean package -DskipTests -B # split the jar into layers RUN java -Djarmode=tools -jar target/*.jar extract --layers --destination extracted # ---------- run ---------- FROM eclipse-temurin:21-jre-alpine WORKDIR /app RUN addgroup -S spring && adduser -S spring -G spring USER spring:spring # least-changing layers first COPY --from=build /build/extracted/dependencies/ ./ COPY --from=build /build/extracted/spring-boot-loader/ ./ COPY --from=build /build/extracted/snapshot-dependencies/ ./ COPY --from=build /build/extracted/application/ ./ EXPOSE 8080 ENV JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=75 -XX:+UseG1GC" ENTRYPOINT ["java", "-jar", "app.jar"]
The layer order matters: dependencies change rarely and your classes change every build, so a code-only change pushes a few hundred kilobytes instead of 60 MB.
Running as root. A container escape then owns the host. Create a user.
Copying the fat jar as one layer. Every deploy re-uploads and
re-downloads all dependencies. Extract layers, as above.
JVM settings inside a container
| Flag | Why |
|---|---|
-XX:MaxRAMPercentage=75 | Heap as a share of the container limit. Never hard-code -Xmx — it will not match the limit you set next month. |
-XX:+UseG1GC | Good general default. Consider ZGC for large heaps and latency-sensitive services. |
-XX:+ExitOnOutOfMemoryError | Die immediately so the orchestrator replaces the pod, rather than limping on. |
-XX:+HeapDumpOnOutOfMemoryError | With -XX:HeapDumpPath pointing at a mounted volume. |
-XX:MaxMetaspaceSize | Metaspace lives outside the heap and is a common source of container OOM-kills. |
Heap is only part of the JVM's footprint. Metaspace, thread stacks (1 MB each), code cache, GC structures and direct byte buffers all live outside it. That is why 75% — not 100% — of the container limit goes to the heap.
Graceful shutdown
server:
shutdown: graceful
spring:
lifecycle:
timeout-per-shutdown-phase: 30s
On SIGTERM, Boot then:
- Stops accepting new requestsThe connector is closed to new connections.
- Lets in-flight requests finishUp to the timeout above.
- Closes the context
@PreDestroy, pools drained, connections returned.
There is a window where the load balancer still sends traffic to a terminating pod. Add a
preStop sleep so readiness has propagated first:
lifecycle:
preStop:
exec:
command: ["sh", "-c", "sleep 10"]
terminationGracePeriodSeconds: 45 # must exceed sleep + shutdown timeout
A Kubernetes deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: bookstore
spec:
replicas: 3
strategy:
rollingUpdate:
maxUnavailable: 0
maxSurge: 1
template:
spec:
terminationGracePeriodSeconds: 45
containers:
- name: bookstore
image: ghcr.io/bitsnippets/bookstore@sha256:abc123… # digest, not a tag
ports:
- containerPort: 8080
- containerPort: 9090 # actuator, not exposed by the Service
env:
- name: SPRING_PROFILES_ACTIVE
value: prod
- name: SPRING_DATASOURCE_PASSWORD
valueFrom:
secretKeyRef: { name: bookstore-db, key: password }
resources:
requests: { memory: "512Mi", cpu: "250m" }
limits: { memory: "1Gi", cpu: "1000m" }
startupProbe: # gives slow starts room, without loosening liveness
httpGet: { path: /actuator/health/liveness, port: 9090 }
failureThreshold: 30
periodSeconds: 2
livenessProbe:
httpGet: { path: /actuator/health/liveness, port: 9090 }
periodSeconds: 10
failureThreshold: 3
readinessProbe:
httpGet: { path: /actuator/health/readiness, port: 9090 }
periodSeconds: 5
failureThreshold: 3
securityContext:
runAsNonRoot: true
readOnlyRootFilesystem: true
allowPrivilegeEscalation: false
capabilities: { drop: ["ALL"] }
Without one, a slow start (migrations, cache warm-up) trips the liveness probe and Kubernetes restarts the pod — forever. The startup probe suspends liveness until the app has come up once.
Database migrations on deploy
spring:
flyway:
enabled: true
locations: classpath:db/migration
baseline-on-migrate: false
validate-on-migrate: true
During a rolling deploy, the old and new versions run simultaneously against the same schema. Dropping a column in the same release that stops using it will break every old pod still serving traffic. Use the expand/contract pattern:
Release 1 add the new column, write to both, read from the old. Release 2 read from the new column. Release 3 drop the old one.
GraalVM native images
# needs a GraalVM JDK with native-image installed ./mvnw -Pnative native:compile ./target/bookstore # Started BookstoreApplication in 0.061 seconds
| JVM jar | Native image | |
|---|---|---|
| Startup | ~2 s | ~0.05 s |
| Memory at idle | ~250 MB | ~60 MB |
| Peak throughput | Higher (JIT optimises hot paths) | Lower |
| Build time | seconds | 3–10 minutes |
| Reflection / dynamic proxies | Free | Needs hints, and some libraries never work |
| Debugging & profiling | Mature tooling | Limited |
Worth it for serverless functions, CLI tools and very high replica counts where memory dominates cost. For a long-running service that starts once a week, the JVM usually wins on throughput and on developer time. Consider CDS first — it is a much cheaper win:
java -Djarmode=tools -jar app.jar extract --destination app java -XX:ArchiveClassesAtExit=app.jsa -Dspring.context.exit=onRefresh -jar app/app.jar java -XX:SharedArchiveFile=app.jsa -jar app/app.jar # ~30-40% faster startup
A CI pipeline that enforces the rule
name: build-and-deploy
on:
push:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with: { java-version: '21', distribution: 'temurin', cache: maven }
- name: Test
run: ./mvnw -B verify # unit + Testcontainers integration tests
- name: Build image
run: |
./mvnw -B spring-boot:build-image \
-Dspring-boot.build-image.imageName=ghcr.io/${{ github.repository }}:${{ github.sha }}
- name: Scan image
uses: aquasecurity/trivy-action@master
with:
image-ref: ghcr.io/${{ github.repository }}:${{ github.sha }}
severity: CRITICAL,HIGH
exit-code: '1'
- name: Push
run: docker push ghcr.io/${{ github.repository }}:${{ github.sha }}
# deploy jobs promote the SAME digest — they never rebuild
deploy-staging:
needs: build
steps:
- run: kubectl set image deployment/bookstore bookstore=ghcr.io/${{ github.repository }}:${{ github.sha }}
Deployment checklist
- One artifact per commit, promoted by digest — never rebuilt per environment.
- Layered image; non-root user; read-only root filesystem.
MaxRAMPercentagerather than a fixed-Xmx.- Graceful shutdown plus a
preStopdelay. - Startup, liveness and readiness probes, all distinct.
- Secrets injected from the platform, never in the image.
- Migrations backwards compatible with the previous release.
- Image vulnerability scanning gating the pipeline.
/actuatoron an internal port only.
Why prefer -XX:MaxRAMPercentage=75 over -Xmx768m?
A fixed -Xmx silently becomes wrong the moment someone changes the container
limit. The percentage adapts, and the 25% headroom covers metaspace, thread stacks, code
cache and direct buffers — the memory that causes "OOM-killed with a healthy heap".