SteelReed

Search

Search posts, questions…

6. DevOps & Operations

The Twelve-Factor App: 12 principles for cloud-ready services, applied to Spring Boot and Kubernetes

The twelve factors from 12factor.net seen from 2026: which ones Kubernetes now handles for you and which are still your job (config and secrets, stateless processes, graceful SIGTERM shutdown, logs to stdout, migrations as admin processes), applied with Java 25, Spring Boot 4 and Docker; plus a JDK-only app tested with SIGTERM and how to review AI-written Dockerfiles and manifests.

18 Nov 20267 min readMid

–

1. The problem

Team A scales from 2 to 20 pods in a minute and rolls back in 30 seconds. Team B rebuilds the jar for each environment; every deploy shows clients dozens of 502s, and scaling up logs users out. Both run on the same Kubernetes; they differ in how they write the app.

2. Key idea

In the cloud, the platform starts, stops and replicates processes at any time. Whatever the app keeps to itself (hard-coded config, in-memory sessions, local files, log files) gets lost or drifts. Think of shipping containers: packed once, handled at any port, only the paperwork (config) differs.

Group 12-factor factors Who handles it
Mostly done by the platform II dependencies (images), VII port binding, VIII concurrency (Deployments, HPA), half of V (registry, rollback) Containers and Kubernetes
Still your code's job III config, VI stateless, IX graceful shutdown, XI logs to stdout You
Process and team work I codebase, X dev/prod parity, XII admin processes Team and pipeline

2.1 The four factors still often wrong

Factor Common violation Fix
III Config application-prod.yml with passwords in the repo environment variables, Secrets mounted as files, a secret manager
VI Processes HttpSession + sticky sessions; files in /tmp/uploads; @Scheduled on every pod Spring Session + Redis; S3; a CronJob or ShedLock, idempotent jobs
IX Disposability shell-form ENTRYPOINT java -jar: the JVM never gets SIGTERM exec form; a preStop sleep; grace period > preStop + drain
XI Logs logging.file.name inside a container JSON to stdout (logging.structured.format.console=ecs)

2.2 When to relax them?

Applied strictly Use when Don't use when
Stateless APIs, consumers databases, brokers: StatefulSets and volumes
Environment variables ordinary config secrets: mounted files are safer
Migrations at startup one service, fast migrations many replicas starting together: run a Job before the rollout

H2 in tests with PostgreSQL in production breaks dev/prod parity: use Testcontainers.

3. In Spring Boot and Kubernetes

YAML
# application.yml (Spring Boot 4): defaults for local, environment overrides in production
spring:
  datasource:
    url: ${DATABASE_URL:jdbc:postgresql://localhost:5432/booking}
    password: ${DATABASE_PASSWORD}          # no default: missing means no startup
  lifecycle:
    timeout-per-shutdown-phase: 20s
server:
  shutdown: graceful
---
# Dockerfile
ENTRYPOINT ["java", "-jar", "/app/app.jar"] # exec: the JVM is PID 1 and receives SIGTERM
---
# deployment.yaml (excerpt)
terminationGracePeriodSeconds: 40           # > preStop 5s + drain 20s
lifecycle:
  preStop:
    sleep: { seconds: 5 }                   # let the ingress drop the pod before closing the listener

Relaxed binding: spring.datasource.url can come from SPRING_DATASOURCE_URL. Other languages: Go catches SIGTERM with signal.NotifyContext then server.Shutdown(ctx); Node.js uses process.on("SIGTERM") then server.close().

What happens when Kubernetes stops a pod
  1. The pod becomes Terminating; Kubernetes simultaneously removes it from Endpoints and runs preStop.
  2. preStop sleeps a few seconds so the ingress and kube-proxy stop sending new requests.
  3. SIGTERM reaches the JVM: Spring reports readiness DOWN, stops accepting new requests, and waits for in-flight ones within timeout-per-shutdown-phase.
  4. If terminationGracePeriodSeconds (counted from the start of preStop) runs out first: SIGKILL, exit 137.

Skip step 2 and the app closes its listener before the ingress stops sending, so clients see 502s. Queue workers NACK in-progress jobs on SIGTERM, and every job must be rerunnable because SIGKILL can still happen.

4. Working with AI

Give the AI: multi-stage Dockerfiles, Deployment and migration Job manifests, moving application-*.yml values into environment variables.

Check in AI-written code:

  • grep -rniE 'password|secret|token' src/main/resources finds no real values.
  • ENTRYPOINT is exec form, or the script ends with exec java.
  • Image tags are commit SHAs or digests, never latest; CI doesn't rebuild per environment.
  • terminationGracePeriodSeconds > preStop + timeout-per-shutdown-phase.
  • Every @Scheduled has a CronJob, a single-replica worker or ShedLock, and the job is idempotent.

5. Exercises

Exercise 1: AI-written "zero downtime"

The AI says "zero-downtime, graceful shutdown enabled":

YAML
# Dockerfile
ENTRYPOINT java -jar /app/app.jar
# deployment.yaml
terminationGracePeriodSeconds: 20
lifecycle: { preStop: { sleep: { seconds: 10 } } }
# application.yml
spring.lifecycle.timeout-per-shutdown-phase: 20s

Find two bugs that still cut requests during deploys.

Solution to Exercise 1
  • Shell-form ENTRYPOINT: PID 1 is /bin/sh -c, the JVM never gets SIGTERM, and graceful shutdown never runs; when the grace period ends, SIGKILL (exit 137). Fix: ENTRYPOINT ["java", "-jar", "/app/app.jar"].
  • Time budget: preStop 10 s + drain 20 s = 30 s, more than the 20 s grace period. Spring gets only about 10 s before SIGKILL. Fix: terminationGracePeriodSeconds: 40 or a shorter drain.
  • Proof: docker stop takes exactly 10 s and exits 137 instead of 143; on the cluster, run load during kubectl rollout restart and count 5xx.

Exercise 2: The AI's proposals

A service runs 4 replicas. The AI proposes: (c) for sessions in HttpSession with sticky sessions, "keep sticky sessions, raise the timeout"; (e) for a reconciliation job @Scheduled(cron = "0 0 2 * * *"), "add synchronized". Which is wrong, and how do you fix it?

Solution to Exercise 2

Both are wrong.

  • (c): sticky sessions still lose sessions whenever a pod is replaced (deploys, scaling, node reclaim). Use Spring Session with Redis or stateless tokens; turn sticky sessions off.
  • (e): synchronized only locks within one JVM; 4 replicas still run the job 4 times at 2 a.m. Make it a CronJob, or use ShedLock (a lock in the DB), and make the job idempotent.

Summary

  • Config from the environment; the repo could be open-sourced now without leaking secrets.
  • Build the image once, promote the same digest.
  • Stateless processes; @Scheduled on several pods needs a lock or a CronJob.
  • Graceful shutdown: exec entrypoint, preStop, a long enough grace period.
  • JSON logs to stdout; Testcontainers instead of H2.

Read more: CI/CD for the backend.

Practice interview questions on this topic

All DevOps & Cloud questions →

Loading comments…
Next on the roadmapLogging for backends: log levels, structured logs, MDC and a centralized log pipeline with ELK or Loki