Sub topic 12
Deploying to Kubernetes
This chapter assumes you can build the executable JAR and container image from earlier chapters. It also assumes you know what Actuator health endpoints, graceful shutdown, and environment-based configuration do in Spring Boot. You need a basic idea of Pods, Deployments, and kubectl. A local cluster such as kind, minikube, or Docker Desktop is enough to follow along.
Kubernetes does not run your JAR directly. It runs a container image and decides when to start it, send it traffic, restart it, and stop it. Your application has to answer three questions for the cluster:
- Where does my configuration come from?
- Am I alive, and am I ready for traffic?
- How do I stop cleanly?
The objects you need
A typical Spring Boot service uses four Kubernetes objects.
| Object | Purpose |
|---|---|
| Deployment | Keeps N identical Pods running and performs rolling updates |
| Service | Gives the Pods one stable name and load-balances across ready Pods |
| ConfigMap | Holds non-secret settings such as the database URL |
| Secret | Holds sensitive values such as the database password |
The image, the probes, and the shutdown timing all live in the Deployment's Pod template. The Deployment is where most deployment problems arise, so this chapter spends most of its time there.
Configuration from the cluster
Earlier chapters kept configuration out of the JAR. In Kubernetes, the Pod spec supplies it as environment variables. Spring Boot's relaxed binding maps SPRING_PROFILES_ACTIVE to spring.profiles.active. The ${DB_URL} and ${DB_PASSWORD} placeholders in application.properties resolve from the environment.
Create the ConfigMap and Secret first:
kubectl create configmap myapp-config \
--from-literal=DB_URL=jdbc:postgresql://db.internal:5432/app
kubectl create secret generic myapp-db \
--from-literal=DB_PASSWORD="$DB_PASSWORD"Passing the password through a shell variable keeps it out of your command text. It can still end up in process listings on shared machines. For real environments, create Secrets from files, from a CI system's secret store, or with an external secrets operator.
A complete Deployment and Service
The manifest below ties the pieces together. Read it once, then the sections that follow explain each choice.
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp
spec:
replicas: 2
selector:
matchLabels:
app: myapp
strategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 0
maxSurge: 1
template:
metadata:
labels:
app: myapp
spec:
terminationGracePeriodSeconds: 45
securityContext:
runAsNonRoot: true
runAsUser: 1000
containers:
- name: myapp
image: myorg/myapp:1.0.0
ports:
- containerPort: 8080
env:
- name: SPRING_PROFILES_ACTIVE
value: prod
- name: JAVA_TOOL_OPTIONS
value: "-XX:MaxRAMPercentage=75"
- name: DB_URL
valueFrom:
configMapKeyRef:
name: myapp-config
key: DB_URL
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: myapp-db
key: DB_PASSWORD
resources:
requests:
cpu: 500m
memory: 768Mi
limits:
memory: 768Mi
startupProbe:
httpGet:
path: /actuator/health/liveness
port: 8080
periodSeconds: 5
failureThreshold: 30
livenessProbe:
httpGet:
path: /actuator/health/liveness
port: 8080
periodSeconds: 10
readinessProbe:
httpGet:
path: /actuator/health/readiness
port: 8080
periodSeconds: 5
lifecycle:
preStop:
exec:
command: ["sleep", "5"]
---
apiVersion: v1
kind: Service
metadata:
name: myapp
spec:
selector:
app: myapp
ports:
- port: 80
targetPort: 8080Apply it with kubectl apply -f myapp.yaml, then watch the rollout with kubectl rollout status deployment/myapp.
Image and user
Use a fixed tag such as 1.0.0 or an image digest, not latest. With a fixed tag, a rollback returns to a known image. With latest, two Pods can run different builds.
The Dockerfile from the earlier chapter creates the user spring by name. With runAsNonRoot: true, Kubernetes cannot verify that a name is not root, so the Pod fails with CreateContainerConfigError. Setting a numeric runAsUser avoids that. Alternatively, create the user with a fixed UID in the image.
Probes
Spring Boot exposes two probe endpoints once management.endpoint.health.probes.enabled=true is set. It enables them automatically when it detects Kubernetes, but setting the property makes the behavior explicit.
/actuator/health/livenessreports whether the application is internally broken. Kubernetes restarts the container when it fails./actuator/health/readinessreports whether the application can accept traffic now. Kubernetes removes the Pod from the Service when it fails, and does not restart it.
The startup probe holds off the other two until the application has started. Here it allows 30 × 5 = 150 seconds. Without it, a slow start can trip the liveness probe and put the Pod in a restart loop.
If you run Actuator on a separate management port with management.server.port, point the probes at that port instead of 8080.
Shutdown and rolling updates
When Kubernetes stops a Pod, two things start at about the same time:
- The Pod is removed from the Service's endpoints. The change takes a moment to reach every node's proxy rules and any load balancer.
- The container receives
SIGTERM, after thepreStophook finishes.
The race matters. If the JVM stops accepting connections immediately, some requests still arrive during the propagation delay and fail. The preStop sleep of 5 seconds gives routing time to catch up before the app begins shutting down.
With server.shutdown=graceful, Spring Boot then switches readiness to REFUSING_TRAFFIC. It stops accepting new requests and waits up to spring.lifecycle.timeout-per-shutdown-phase for in-flight requests to finish.
The timings must fit together:
preStop (5 s) + shutdown timeout (30 s) = 35 s < terminationGracePeriodSeconds (45 s)The default terminationGracePeriodSeconds is 30 seconds. If the Spring timeout is also 30 seconds, SIGKILL can arrive before the application finishes draining. That is why the manifest sets 45.
maxUnavailable: 0 with maxSurge: 1 makes the rollout start a new Pod and wait for it to become ready before it stops an old one. Readiness is what makes this safe, so a wrong readiness path can stall or break a rollout.
Memory and CPU
The container limit is a hard cap. If the JVM's total memory use passes 768 MiB, the kernel kills the process with an out-of-memory (OOM) kill. The container reports OOMKilled and exit code 137.
The heap is only part of JVM memory. Metaspace, thread stacks, and direct buffers need room too. -XX:MaxRAMPercentage=75 sizes the heap from the container limit, so the heap grows with the limit instead of using a fixed -Xmx. This leaves about a quarter for everything else. Do not set the heap to 100% of the limit.
Setting the memory request equal to the limit keeps memory usage predictable. The manifest leaves out a CPU limit on purpose. CPU limits throttle the JVM, which hurts startup and garbage collection. Many teams set only a CPU request. Note that the JVM sizes thread pools from the CPU count it sees, so a CPU limit below 1 core can make it behave as a single-CPU machine.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Pod in `CreateContainerConfigError` | Non-numeric user with `runAsNonRoot`, or a missing ConfigMap or Secret | Set `runAsUser` and check object names with `kubectl describe pod` |
| Pod restarts during startup | Liveness probe starts before the app is up | Add or lengthen the startup probe |
| `OOMKilled`, exit code 137 | Heap plus non-heap memory exceeds the limit | Raise the limit or lower `MaxRAMPercentage` |
| Pod running but never `Ready` | Wrong probe path or port, or Actuator not exposed | Call the probe URL with `kubectl port-forward` |
| Errors during rollouts | Grace period shorter than preStop plus shutdown timeout | Recompute the timing budget |
| All Pods restart when the database fails | Database check in the liveness group | Remove it from liveness |
Useful commands for diagnosis:
kubectl describe pod -l app=myapp
kubectl logs deployment/myapp --previous
kubectl port-forward deployment/myapp 8080:8080
curl -s localhost:8080/actuator/health/readiness--previous shows logs from the last crashed container, which is where the startup failure usually appears.
Exercise
Your Spring Boot setting is spring.lifecycle.timeout-per-shutdown-phase=60s, and the Deployment has a 5-second preStop sleep. What is the smallest sensible terminationGracePeriodSeconds, and what happens to in-flight requests if you leave the default of 30?
Show answer
The budget is preStop plus shutdown timeout: 5 + 60 = 65 seconds, so the value must be greater than 65 (for example 75, leaving some margin). With the default of 30, Kubernetes sends SIGKILL about 30 seconds after termination begins, even though Spring is still waiting for requests to finish. Any request still running at that point is cut off, which defeats graceful shutdown.
Exercise
A teammate adds a database check to the liveness probe group. The database goes down for two minutes. What does the cluster do, and where should the check go instead?
Show answer
The liveness probe fails on every Pod, so Kubernetes restarts all of them. The restarted Pods also fail until the database returns, which causes restart loops and loses capacity that was healthy apart from the dependency. If the dependency check belongs anywhere, it goes in the readiness group, so Pods are only taken out of the Service and not restarted.