Video in progress
You are running a daily report job built with Spring Boot as a Kubernetes CronJob. What should you pay attention to?
The application must exit on its own with an exit code when the work is done, two copies must not run at the same time (concurrencyPolicy: Forbid), and retries (backoffLimit) and the time limit (activeDeadlineSeconds) must be explicit. If the job is idempotent, a rerun is safe.
📖 Answer
apiVersion: batch/v1
kind: CronJob
metadata:
name: daily-report
spec:
schedule: "0 2 * * *"
timeZone: "Asia/Tashkent" # stable since K8s 1.27
concurrencyPolicy: Forbid
startingDeadlineSeconds: 600
jobTemplate:
spec:
backoffLimit: 2
activeDeadlineSeconds: 3600
template:
spec:
restartPolicy: Never
containers:
- name: report
image: registry.example.uz/report-job:2.3.1
args: ["--spring.main.web-application-type=none"]
The most common mistake on the Spring side is a job that never finishes. If the context has a Kafka listener, @Scheduled, or a non-daemon thread pool, the JVM keeps running after the work is done, and the pod hangs until activeDeadlineSeconds. Exit explicitly when the work is done:
@SpringBootApplication
public class ReportJob {
public static void main(String[] args) {
var ctx = SpringApplication.run(ReportJob.class, args);
// exits with the code provided by the ExitCodeGenerator beans
System.exit(SpringApplication.exit(ctx));
}
}
On failure, exit with a non-zero code: Kubernetes uses that to treat the Job as failed and retries according to backoffLimit.
Other subtle points:
- a CronJob guarantees "roughly once": rarely, but two Jobs can be created for one schedule slot, or none. Make writing the result idempotent (for example, an upsert by
report_date); - with
Forbid, if the previous job is still running, the new one is silently skipped; - if a node is drained, the job pod also gets SIGTERM. Split a long job into pieces and save how far it got;
- the worst case is a job that fails silently. Set an alert on
kube_cronjob_status_last_successful_timefrom kube-state-metrics: "has not succeeded for 25 hours".
Sign up to mark studied questions and save your progress.