Sign In

Curriculum 18: Jobs & CronJobs

Cleanup Policies

10 min · 25 XP

Job Cleanup Policies

Completed and failed Jobs leave behind pod resources that accumulate over time. Kubernetes provides several mechanisms to automatically clean up finished Jobs and their pods.

TTL Controller for Finished Jobs

The TTL-after-finished controller automatically deletes Jobs after a specified time. Set ttlSecondsAfterFinished in the Job spec:

apiVersion: batch/v1
kind: Job
metadata:
  name: short-task
spec:
  ttlSecondsAfterFinished: 3600
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: worker
          image: busybox
          command: ["sh", "-c", "echo done"]

This Job is automatically deleted 3600 seconds (1 hour) after it finishes, whether it succeeded or failed.

kubectl apply -f job-with-ttl.yaml
kubectl get jobs --watch

CronJob History Limits

CronJobs have built-in history controls:

spec:
  successfulJobsHistoryLimit: 3
  failedJobsHistoryLimit: 1
  • successfulJobsHistoryLimit -- number of successful Job records to keep (default: 3)
  • failedJobsHistoryLimit -- number of failed Job records to keep (default: 1)

Setting either to 0 deletes Jobs immediately after completion or failure.

Manual Cleanup

# Delete a specific completed job and its pods
kubectl delete job data-migration

# Delete all completed jobs in a namespace
kubectl delete jobs --field-selector status.successful=1

# Delete all jobs (use with caution)
kubectl delete jobs --all -n batch-namespace

Checking Accumulated Jobs

# Count jobs per namespace
kubectl get jobs -A --no-headers | wc -l

# Find old completed jobs
kubectl get jobs --sort-by=.status.completionTime

Without proper cleanup policies, old Job objects and their pod logs consume etcd storage and clutter command output. Always configure TTL or history limits for production workloads.