5.5.1 创建Job对象

Job 控制器的spec字段内嵌的必要字段仅为template,它的使用方式与Deployment等控制器并无不同。Job会为其Pod对象自动添加“Job-name=JOB_NAME”和“conttoller-uid=UID”标签,并使用标签选择器完成对controller-uid标签的关联。需要注意的是,Job位于API群组“batch/v1”之内。下面的资源清单文件(job-example.yaml)中定义了一个Job控制器:

apiVersion: batch/v1
kind: Job
metadata:
  name: job-example
spec:
  template:
    spec:
      containers:
      - name: myjob
        image: alpine
        command:
          - /bin/sh
          - -c
          - sleep 120
      restartPolicy: Never

Pod 模板中的spec.restartPolicy默认为“Always”,这对Job控制器来说并不适用,因此必须在Pod模板中显式设定restartPolicy属性的值为“Never”或“OnFailure”。

使用“kubectl create”或“kubectl apply”命令完成创建后即可查看相关的任务状态,COMPLETIONS字段右侧数字表示期望并运行的Pod资源数量,而左侧则表示成功完成的Job数:

**[terminal]
**[delimiter $ ]**[command kubectl get jobs.batch job-example]
NAME          COMPLETIONS   DURATION   AGE
job-example   0/1           58s        58s

相关的Pod资源能够以Job控制器名称为标签进行匹配:

**[terminal]
**[delimiter $ ]**[command kubectl get pods -l job-name=job-example]
NAME                READY   STATUS    RESTARTS   AGE
job-example-wfw8s   1/1     Running   0          87s

其详细信息中可显示所使用的标签选择器及配置的Pod资源的标签,具体如下:

**[terminal]
**[delimiter $ ]**[command kubectl describe jobs job-example]
Name:           job-example
Namespace:      default
Selector:       controller-uid=b2e2d178-b9c1-4511-b4f8-9792e2ff0bbd
Labels:         controller-uid=b2e2d178-b9c1-4511-b4f8-9792e2ff0bbd
                job-name=job-example
Annotations:    <none>
Parallelism:    1
Completions:    1
Start Time:     Mon, 14 Sep 2020 10:45:44 +0800
Completed At:   Mon, 14 Sep 2020 10:48:05 +0800
Duration:       2m21s
Pods Statuses:  0 Running / 1 Succeeded / 0 Failed
Pod Template:
  Labels:  controller-uid=b2e2d178-b9c1-4511-b4f8-9792e2ff0bbd
           job-name=job-example
  Containers:
   myjob:
    Image:      alpine
    Port:       <none>
    Host Port:  <none>
    Command:
      /bin/sh
      -c
      sleep 120
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Events:
  Type    Reason            Age    From            Message
  ----    ------            ----   ----            -------
  Normal  SuccessfulCreate  4m21s  job-controller  Created pod: job-example-wfw8s
  Normal  Completed         2m     job-controller  Job completed

两分钟后,等待sleep命令执行完成并成功退出后,Pod资源即转换为Completed状态,再使用“kubectl get pods”命令查看:

**[terminal]
**[delimiter $ ]**[command kubectl get pods -l job-name=job-example]
NAME                READY   STATUS      RESTARTS   AGE
job-example-wfw8s   0/1     Completed   0          7m

此时,如果使用“kubectl get jobs”显示job-example的相关信息,那么其COMPLETIONS字段左侧的数字就不再为“0”。

results matching ""

    No results matching ""