Chapter 14

Packaging and deployment

One artifact, promoted unchanged from dev to production, configured entirely by its environment. Everything in this chapter serves that single rule.

⏱ 20 min readLevel: intermediate
Pipeline from source to executable jar to layered image to registry to platform, with layer breakdown and a JVM versus native comparison
Build once, promote the same digest. Only environment variables change.

The executable jar

terminal
./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
the structure of a fat jar
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

terminal
./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.

Dockerfile
# ---------- 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.

Two container mistakes that cost real money

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

FlagWhy
-XX:MaxRAMPercentage=75Heap as a share of the container limit. Never hard-code -Xmx — it will not match the limit you set next month.
-XX:+UseG1GCGood general default. Consider ZGC for large heaps and latency-sensitive services.
-XX:+ExitOnOutOfMemoryErrorDie immediately so the orchestrator replaces the pod, rather than limping on.
-XX:+HeapDumpOnOutOfMemoryErrorWith -XX:HeapDumpPath pointing at a mounted volume.
-XX:MaxMetaspaceSizeMetaspace lives outside the heap and is a common source of container OOM-kills.
The container was OOM-killed but the heap looked fine

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

application.yml
server:
  shutdown: graceful

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

On SIGTERM, Boot then:

  1. Stops accepting new requestsThe connector is closed to new connections.
  2. Lets in-flight requests finishUp to the timeout above.
  3. Closes the context@PreDestroy, pools drained, connections returned.
Readiness must flip before the shutdown starts

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

deployment.yaml
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"] }
Use a startup probe, not a generous liveness probe

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

application.yml
spring:
  flyway:
    enabled: true
    locations: classpath:db/migration
    baseline-on-migrate: false
    validate-on-migrate: true
Migrations must be backwards compatible

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

terminal
# needs a GraalVM JDK with native-image installed
./mvnw -Pnative native:compile

./target/bookstore
# Started BookstoreApplication in 0.061 seconds
JVM jarNative image
Startup~2 s~0.05 s
Memory at idle~250 MB~60 MB
Peak throughputHigher (JIT optimises hot paths)Lower
Build timeseconds3–10 minutes
Reflection / dynamic proxiesFreeNeeds hints, and some libraries never work
Debugging & profilingMature toolingLimited

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:

Class Data Sharing (Boot 3.3+)
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

.github/workflows/deploy.yml
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.
  • MaxRAMPercentage rather than a fixed -Xmx.
  • Graceful shutdown plus a preStop delay.
  • 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.
  • /actuator on 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".