Working with Kubernetes Jobs and Cronjobs

Kubernetes jobs execute one time task. A Job creates one or more Pods and will continue to retry execution of the Pods until a specified number of them successfully terminate.

Related content:

Running an example Job

apiVersion: batch/v1
kind: Job
metadata:
  name: query-k8s-apps
spec:
  ttlSecondsAfterFinished: 100
  template:
    spec:
      containers:
      - args:
        - -c
        - /apps/query-k8s-apps -n dev,qa
        command:
        - /bin/sh
      - name: query-k8s-apps
        image: ektowett/query-k8s-apps:latest
        env:
        - name: CONTEXTS
          value: cloud_okteto_com
        - name: DB_PASSWORD
          valueFrom:
            secretKeyRef:
              key: password
              name: rails-mariadb-secret
      restartPolicy: Never
  backoffLimit: 4

Execute

kubectl apply -f job.yaml

Output job as yaml:

kubectl get job myjob -o yaml

Job termination and cleanup

When a Job completes, no more Pods are created, but the Pods are not deleted either. Keeping them around allows you to still view the logs of completed pods to check for errors, warnings, or other diagnostic output. The job object also remains after it is completed so that you can view its status. It is up to the user to delete old jobs after noting their status. Delete the job with kubectl (e.g. kubectl delete jobs/pi or kubectl delete -f ./job.yaml). When you delete the job using kubectl, all the pods it created are deleted too.

CronJob

A CronJob creates Jobs on a repeating schedule. One CronJob object is like one line of a crontab (cron table) file. It runs a job periodically on a given schedule, written in Cron format.

Example

apiVersion: batch/v1
kind: CronJob
metadata:
  name: query-k8s-apps
spec:
  schedule: "*/5 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: query-k8s-apps
            image: ${dockerRegistry}:${env.BRANCH_NAME}-${COMMIT_ID.take(10)}
            imagePullPolicy: IfNotPresent
            env:
            - name: CONTEXTS
              value: cloud_okteto_com
            - name: APP_URL
              value: http://iserve.kip0127.cloud.okteto.net/api/v1/k8s-versions
            - name: NAMESPACES
              value: kip0127
          restartPolicy: OnFailure

Get a list of cronjobs present:

kubectl get cronjobs
Last updated on Oct 14, 2024 11:46 +0300
comments powered by Disqus
Citizix Ltd
Built with Hugo
Theme Stack designed by Jimmy