🦉
Programming Notes
  • My Programming Notes
  • CKA Exam Preparation
    • Certified Kubernetes Administrator
    • Setup Minikube
    • Network Design Principles
    • Role-Based Access Control (RBAC)
    • Namespace
    • Resource Quota
    • Pod
    • Deployment
    • Deployment: Rollout
    • ConfigMap
    • Service
    • Service: kubectl expose
    • Pod: Resources Management
    • Pod & Container: Quality of Service Class
    • Pod & Container: Probes
    • Limit Range
    • Scaling: Manual
    • Scaling: Horizontal Pod Autoscaler
    • Persistent Volume & Claim
    • Secret
    • Ingress: Routing
    • Ingress: TLS
    • Ingress: Rate Limit
    • Ingress: Basic Auth
    • Ingress: CRD (Custom Resource Definition)
    • Job
    • CronJob
    • Mutli-Node Cluster
  • Golang
    • Generics
    • Context
    • Goroutines and Channels in Go
    • Goroutine: Concurrency vs Parallelism
    • Goroutine: Performance & Tradeoffs
    • JSON: omitzero
  • Rust
    • Arrays & Slices
    • Closures
    • Generics & Traits
    • Iterators
    • Run Code Simultaneously
    • String vs &str
    • Tests
    • Rustlings Exercises
      • Variables
      • Functions
      • If
      • Primitive Types
      • Vectors
      • Move Semantics
      • Structs
      • Enums and Matching Pattern
      • Strings
      • Modules
      • Hashmaps
      • Options
      • Error Handling
      • Generics
      • Traits
      • Lifetimes
      • Tests
      • Iterators
      • Smart Pointers
      • Threads
      • Macros
      • Quiz 1
      • Quiz 2
      • Quiz 3
  • Software Engineering
    • CAP Theorem
    • Circuit Breaker
    • Decoupling
    • GraphQL: Query Caching
    • HMAC Signature
    • Idempotency
    • Monolith VS Microservice
    • OWASP Top 10 2021
    • PCI DSS
    • PostgreSQL: Partitioning
    • PostgreSQL: Replication
    • Protobuf & gRPC
    • Redis: Streams
    • Resource Scaling
    • Signed URL
    • SOLID
    • Stack VS Heap
    • Stateful VS Stateless
  • Site Reliability Engineering
    • Chaos Engineering
    • Distributed Tracing
    • Kubernetes (k8s)
    • SLA, SLO, and SLI Metrics
    • Site Reliability Engineer
  • Others
    • FFMPEG Cheat sheet
Powered by GitBook
On this page
  • Create CronJob to Dump Database
  • Manually Trigger Job
  • References
  1. CKA Exam Preparation

CronJob

PreviousJobNextMutli-Node Cluster

Last updated 3 months ago

Previously we already create a Job to backup the postgres database service that we have. But its inconvenient to run this job manually every time we want to backup. We can use CronJob for this.

CronJob create a job on a repeating schedule. It runs a Job periodically on a given schedule, written in Cron format.

# * * * * * <command to execute>
# | | | | |
# | | | | day of the week (0–6) (Sunday to Saturday; 
# | | | month (1–12)             7 is also Sunday on some systems)
# | | day of the month (1–31)
# | hour (0–23)
# minute (0–59)

I usually use this website () to check if my cron format is correct and will behave as expected or not.

Create CronJob to Dump Database

Lets create a CronJob that will run a job we previously created to dump PostgreSQL database. The basic CronJob definition/configuration is simple.

apiVersion: batch/v1
kind: CronJob
metadata:
  name: postgres-backup
spec:
  schedule: "0 0 * * *"  # Runs at midnight daily
  jobTemplate:

We just need to define our CronJob above, specify the schedule (in here I use 0 0 * * * so it will run every midnight), and then put the job definition we previously created into the jobTemplate section.

Your full file should looks like this.

apiVersion: batch/v1
kind: CronJob
metadata:
  name: postgres-backup
spec:
  schedule: "0 0 * * *"
  jobTemplate:
    spec:
      ttlSecondsAfterFinished: 60
      template:
        spec:
          containers:
          - name: pg-backup
            image: postgres:17
            command: ["/bin/sh", "-c"]
            args:
            - |
              echo "Starting PostgreSQL backup..."
              pg_dump -h postgres.default.svc.cluster.local -d mydb > /backup/postgres_backup_$(date +%Y%m%d%H%M%S).sql
              echo "Backup completed!"
            env:
            - name: PGUSER
              valueFrom:
                secretKeyRef:
                  name: postgres-secret
                  key: POSTGRES_USER
            - name: PGPASSWORD
              valueFrom:
                secretKeyRef:
                  name: postgres-secret
                  key: POSTGRES_PASSWORD
            volumeMounts:
            - mountPath: /backup
              name: backup-storage
          volumes:
          - name: backup-storage
            persistentVolumeClaim:
              claimName: postgres-backup-pvc
          restartPolicy: Never

Lets name the file as postgres-backup-cronjob.yaml then apply the file.

➜ kubectl apply -f postgres-backup-cronjob.yaml 
cronjob.batch/postgres-backup created

Validate that your CronJob is properly created.

➜ kubectl get cronjob                          
NAME              SCHEDULE    TIMEZONE   SUSPEND   ACTIVE   LAST SCHEDULE   AGE
postgres-backup   0 0 * * *   <none>     False     0        <none>          3s

As you can see above we now have a CronJob that will create a Job every midnight to run pg_dump. We also can explicitly specify a timezone or if we left it empty it will be defaulted to local timezone.

For CronJobs with no time zone specified, the kube-controller-manager interprets schedules relative to its local time zone.

Manually Trigger Job

Waiting the job to run at midnight is not ideal when we want to test if our CronJob will run properly or not. In this case we can manually trigger the scheduled job using this command below.

➜ kubectl create job --from=cronjob/postgres-backup backup-manual
job.batch/backup-manual created

Lets get list of the job and you should see the manually triggered job. Like before, we can get the job logs to make sure that it run successfully.

➜ kkubectl get jobs
NAME            STATUS     COMPLETIONS   DURATION   AGE
backup-manual   Complete   1/1           4s         5s
➜ kkubectl logs jobs/backup-manual 
Starting PostgreSQL backup...
Backup completed!

References

crontab.guru
https://kubernetes.io/docs/concepts/workloads/controllers/cron-jobs/
https://en.wikipedia.org/wiki/Cron