Spring Boot on Kubernetes

Deploy production Spring Boot apps on Kubernetes: Actuator health groups, JVM container memory limits, ConfigMaps, Secrets, and graceful shutdown.

Deploying Spring Boot microservices on Kubernetes requires aligning the Java Virtual Machine (JVM) memory architecture with Linux container cgroups, configuring Spring Boot Actuator health groups for Kubernetes probes, externalizing configuration through ConfigMaps and Secrets, and implementing graceful termination to avoid dropped HTTP connections during rolling updates.

Core Integration Architecture

Modern Spring Boot versions (2.3+ and 3.x) feature native container and Kubernetes awareness, including preconfigured Actuator endpoints and support for container memory limits:

Requirement Spring Boot Mechanism Kubernetes Resource / Field
Liveness Check /actuator/health/liveness (LivenessState) livenessProbe.httpGet
Readiness Check /actuator/health/readiness (ReadinessState) readinessProbe.httpGet
Externalized Config application.properties / SPRING_CONFIG_IMPORT ConfigMap volume mount or envFrom
Sensitive Credentials Database passwords / API tokens Secret volume mount or valueFrom
Memory Allocation -XX:MaxRAMPercentage=75.0 resources.requests and resources.limits
Graceful Shutdown server.shutdown=graceful lifecycle.preStop + terminationGracePeriodSeconds

JVM Memory Management in Containers

The JVM allocates memory across multiple distinct areas: Heap (object storage), Metaspace (class definitions), Thread Stacks (1MB per thread default), Direct Buffers (NIO), and JVM Native Overhead.

To prevent Linux kernel OOMKilled (Exit Code 137), container limits must accommodate both heap and non-heap memory:

$$\text{Container Memory Limit} \ge \frac{\text{Max Heap (Xmx)}}{0.70 \text{ to } 0.75}$$

Setting -XX:+UseContainerSupport and -XX:MaxRAMPercentage=75.0 instructs the OpenJDK runtime to dynamically calculate maximum heap based on the container cgroup limit rather than the total physical node RAM.

Production Kubernetes Manifests

apiVersion: v1
kind: ConfigMap
metadata:
  name: order-service-config
  namespace: production
data:
  application.yaml: |
    server:
      port: 8080
      shutdown: graceful
    spring:
      lifecycle:
        timeout-per-shutdown-phase: 30s
    management:
      endpoints:
        web:
          exposure:
            include: health,info,prometheus
      endpoint:
        health:
          probes:
            enabled: true
          show-details: never
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: order-service
  namespace: production
spec:
  replicas: 3
  selector:
    matchLabels:
      app: order-service
  template:
    metadata:
      labels:
        app: order-service
    spec:
      terminationGracePeriodSeconds: 45
      containers:
        - name: order-service
          image: order-service:3.2.0
          env:
            - name: JAVA_TOOL_OPTIONS
              value: >-
                -XX:+UseContainerSupport
                -XX:MaxRAMPercentage=75.0
                -XX:InitialRAMPercentage=75.0
                -XX:+ExitOnOutOfMemoryError
            - name: SPRING_CONFIG_ADDITIONAL_LOCATION
              value: "file:/config/"
            - name: DB_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: db-credentials
                  key: password
          ports:
            - containerPort: 8080
          startupProbe:
            httpGet:
              path: /actuator/health/liveness
              port: 8080
            initialDelaySeconds: 10
            periodSeconds: 5
            failureThreshold: 12
          livenessProbe:
            httpGet:
              path: /actuator/health/liveness
              port: 8080
            periodSeconds: 10
            failureThreshold: 3
          readinessProbe:
            httpGet:
              path: /actuator/health/readiness
              port: 8080
            periodSeconds: 5
            failureThreshold: 2
          lifecycle:
            preStop:
              exec:
                command: ["sh", "-c", "sleep 10"]
          resources:
            requests:
              cpu: 500m
              memory: 1Gi
            limits:
              cpu: 1000m
              memory: 1Gi
          volumeMounts:
            - name: config-vol
              mountPath: /config
              readOnly: true
      volumes:
        - name: config-vol
          configMap:
            name: order-service-config

Common Mistakes

  • Hardcoding -Xmx in Dockerfiles: Specifying -Xmx512m hardcodes heap size in the image, rendering container resource limit adjustments in Kubernetes manifests ineffective.
  • Squeezing memory limits without off-heap headroom: Setting container memory limit equal to -Xmx causes the Linux cgroup to terminate the Pod (OOMKilled) when Metaspace or thread stack usage climbs.
  • Pointing Liveness Probes to /actuator/health: The generic /actuator/health endpoint tests database and Redis connections. If an external DB blips, all Spring Boot Pods fail liveness and enter restart loops.
  • Missing graceful shutdown: Without server.shutdown=graceful and a preStop hook, active HTTP transactions are severed immediately when Pods are terminated during rollouts.

Best Practices

  • Always use Spring Boot Actuator dedicated probe paths: /actuator/health/liveness and /actuator/health/readiness.
  • Set -XX:MaxRAMPercentage=75.0 via JAVA_TOOL_OPTIONS to allow 25% memory headroom for non-heap allocations.
  • Enable -XX:+ExitOnOutOfMemoryError so the JVM exits immediately on heap exhaustion, allowing Kubernetes to restart the failed Pod cleanly.
  • Mount configuration files using ConfigMaps and Secrets rather than rebuilding images for environment-specific properties.

Interview Questions

1. How does Spring Boot Actuator integrate with Kubernetes Liveness and Readiness Probes?

Spring Boot 2.3+ natively exposes /actuator/health/liveness (backed by LivenessState) and /actuator/health/readiness (backed by ReadinessState). When running in Kubernetes, these endpoints are auto-enabled. Liveness checks if the internal application context is intact, while readiness reflects whether the application has finished startup and is ready to process traffic.

2. Why is using -XX:MaxRAMPercentage preferred over -Xmx in Kubernetes?

-Xmx hardcodes an absolute memory limit (e.g. -Xmx1g). If an administrator changes the container memory limit in the Kubernetes manifest to 2Gi, the JVM still only uses 1Gi. Conversely, if the container limit is reduced to 800Mi, the JVM will attempt to allocate 1Gi and be killed by the Linux cgroup OOM-killer. -XX:MaxRAMPercentage=75.0 dynamically scales the heap to 75% of whatever memory limit is allocated to the container.

3. Why must container memory limits exceed the JVM Max Heap size?

The JVM consumes significant memory outside the heap: Metaspace (class metadata), thread execution stacks (1MB per thread), garbage collector metadata, direct byte buffers (Netty/NIO), and native libraries. If container limits equal -Xmx, any non-heap memory allocation will cause total container memory to exceed the limit, triggering an immediate OOMKilled exit.

4. How does graceful shutdown work in Spring Boot on Kubernetes?

When server.shutdown=graceful is enabled, the embedded web server (Tomcat/Jetty/Netty) stops accepting new requests and allows active in-flight requests a grace period (configured via spring.lifecycle.timeout-per-shutdown-phase) to complete before terminating the JVM.

5. Why should you combine a preStop hook with Spring Boot graceful shutdown?

Kubernetes removes the Pod from Service Endpoints and sends the SIGTERM signal concurrently. Without a preStop: sleep 10 hook, the Spring Boot app may reject new requests while kube-proxy iptables rules are still routing incoming connections to the Pod, resulting in HTTP 502/503 errors.

6. What is the purpose of -XX:+ExitOnOutOfMemoryError?

When a Java application encounters an OutOfMemoryError, the JVM may remain running in an unstable, corrupted state without processing requests. Adding -XX:+ExitOnOutOfMemoryError causes the JVM process to exit immediately on OOM, enabling Kubernetes to detect the termination and start a fresh container instance.

Summary

  • Spring Boot Actuator provides specialized /actuator/health/liveness and /readiness endpoints.
  • Manage JVM memory using -XX:MaxRAMPercentage=75.0 to respect container cgroups.
  • Allocate at least 25% memory headroom above heap for Metaspace, threads, and off-heap allocations.
  • Combine server.shutdown=graceful with a preStop sleep hook for zero-downtime rolling updates.

Continue Learning

Previous: RBAC | Next: Kubernetes Monitoring

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.