k8s之Job与CronJob

作草分茶About 1 min

k8s之Job与CronJob

简单的 Job

一个典型的 Job 配置文件如下:

apiVersion: batch/v1
kind: Job
metadata:
  name: job-pi
spec:
  template:
    spec:
      containers:
        - name: job-pi
          image: resouer/ubuntu-bc
          command: [ 'sh', '-c', 'echo "scale=10000; 4*a(1)" | bc -l ' ]
      restartPolicy: OnFailure

创建 Job

$ kubectl apply -f job-pi.yaml

查看 job,可以看到 job 已经创建了,完成数量为0

$ kubectl get job             
NAME     COMPLETIONS   DURATION   AGE
job-pi   0/1           8s         8s

看看 Job 的详情信息

$ kubectl describe jobs/job-pi
Name:             job-pi
Namespace:        default
Selector:         controller-uid=09473d71-64ca-4342-84fc-83f721d1fe92
Labels:           controller-uid=09473d71-64ca-4342-84fc-83f721d1fe92
                  job-name=job-pi
Annotations:      <none>
Parallelism:      1
Completions:      1
Completion Mode:  NonIndexed
Start Time:       Sat, 21 May 2022 12:52:52 +0800
Pods Statuses:    1 Running / 0 Succeeded / 0 Failed
Pod Template:
  Labels:  controller-uid=09473d71-64ca-4342-84fc-83f721d1fe92
           job-name=job-pi
  Containers:
   job-pi:
    Image:      resouer/ubuntu-bc
    Port:       <none>
    Host Port:  <none>
    Command:
      sh
      -c
      echo "scale=10000; 4*a(1)" | bc -l 
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Events:
  Type    Reason            Age   From            Message
  ----    ------            ----  ----            -------
  Normal  SuccessfulCreate  18s   job-controller  Created pod: job-pi--1-fnbcg

看到 Events 里,Job 创建完成了,并且创建了一个名为 job-pi--1-fnbcg 的 Pod。

看下是不是真有这个 pod 被创建了

$ kubectl get pod                       
NAME              READY   STATUS    RESTARTS   AGE
job-pi--1-fnbcg   1/1     Running   0          53s

可以看到该 Pod 确实被创建了,正在运行中。

过一会儿再看下,发现已经完成了。

$ kubectl get pod 
NAME              READY   STATUS      RESTARTS   AGE
job-pi--1-fnbcg   0/1     Completed   0          7m52s

看下日志,确实已经计算完成了

$ kubectl logs job-pi--1-fnbcg
3.14159265358979323846264338327950288419716939937510582…………

回头再看下 job 的状态,这时候发现已经完成了,耗时2m1s。

NAME     COMPLETIONS   DURATION   AGE
job-pi   1/1           2m1s       10m

参数

spec:
  # 失败重试次数
  backoffLimit: 4
  # 最大并行数量
  parallelism: 2
  # 最小完成数
  completions: 4
  # 最长运行时间
  activeDeadlineSeconds: 100

Cron Job