Challenge - CronJob
- Docker & Kubernetes course
- Advanced
- Lesson 68/70
- 5 min
Write a CronJob that runs daily.
Challenge: a safe scheduled backup
You'll write a CronJob that takes a backup of the database every night. Requirements:
- Every day at 02:30 (Istanbul time)
- A new one mustn't start if the previous backup hasn't finished
- At most 2 attempts, at most 30 minutes
- The backup is written to a PVC; the password comes from a Secret
pg_dump -h db -U app app | gzip > /yedek/app-$(date +%F).sql.gzPractice The top of the CronJob
Write the top part of a CronJob's spec section (starting with spec:): schedule: "30 2 * * *", timeZone: "Europe/Istanbul", concurrencyPolicy: Forbid; under jobTemplate.spec, backoffLimit: 1 and activeDeadlineSeconds: 1800.
Starter code
# buraya yazSample solution
spec:
schedule: "30 2 * * *"
timeZone: "Europe/Istanbul"
concurrencyPolicy: Forbid
jobTemplate:
spec:
backoffLimit: 1
activeDeadlineSeconds: 1800Expected output
cronjob.batch/gece-yedek configured
Practice The backup pod template
Write the same CronJob's pod template spec section (starting with spec:): restartPolicy: OnFailure; a yedek volume from the yedekler PVC; container named yedek, image postgres:16; the PGPASSWORD variable from the POSTGRES_PASSWORD key of the db-gizli Secret; mount yedek at /yedek.
Starter code
# buraya yazSample solution
spec:
restartPolicy: OnFailure
volumes:
- name: yedek
persistentVolumeClaim:
claimName: yedekler
containers:
- name: yedek
image: postgres:16
env:
- name: PGPASSWORD
valueFrom:
secretKeyRef:
name: db-gizli
key: POSTGRES_PASSWORD
volumeMounts:
- name: yedek
mountPath: /yedekExpected output
$ kubectl create job yedek-elle --from=cronjob/gece-yedek job.batch/yedek-elle created $ kubectl logs job/yedek-elle pg_dump: tamamlandı (12.4 MB)
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the most reliable way to notice a failed backup?
- Deleting the CronJob
- Setting an alert on the Job's failed state or the last success time Correct answer
- Checking the logs by hand every morning
- Doing nothing
Explanation: The kube_cronjob_status_last_successful_time metric suits this.
2 Set the schedule's time zone to Istanbul.
spec:
schedule: "30 2 * * *"
timeZone: ____
spec:
schedule: "30 2 * * *"
timeZone: "Europe/Istanbul"
Explanation: An IANA time zone name is used.
3 Match.
| Term | Meaning |
|---|---|
"30 2 * * *" |
Every day 02:30 |
Forbid |
Prevent overlap |
backoffLimit: 1 |
At most 2 attempts |
activeDeadlineSeconds: 1800 |
30-minute limit |