完整的k8s教程可访问:https://www.zfcdn.xyz/showinfo-3-36255-0.html
部署job(一次性任务)
编辑myjob.yaml 并写入如下代码
#Never 程序退出了就不再重启了,不管正确还是错误退出apiVersion: batch/v1
kind: Job
metadata:
name: myjob
spec:
template:
metadata:
name: myjob
spec:
containers:
- name: hello
image: busybox
command: ["echo","hello k8s job"]
restartPolicy: Never
kubectl apply -f myjob.yaml
查看结果。[root@master ~]# kubectl apply -f myjob.yaml
job.batch/myjob created
可以通过pod日志查看是否有执行成功。[root@master ~]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
ds-test-crpsf 1/1 Running 0 29m 10.244.3.29 node3 <none> <none>
ds-test-glnql 1/1 Running 0 29m 10.244.1.34 node2 <none> <none>
myjob-fp4bl 0/1 Completed 0 105s 10.244.1.35 node2 <none> <none>
web-statefulset-0 1/1 Running 0 51m 10.244.3.27 node3 <none> <none>
web-statefulset-1 1/1 Running 0 50m 10.244.1.33 node2 <none> <none>
web-statefulset-2 1/1 Running 0 50m 10.244.3.28 node3 <none> <none>
[root@master ~]# kubectl get jobs
NAME COMPLETIONS DURATION AGE
myjob 1/1 27s 2m2s
执行结果如下:kubectl logs myjob-fp4bl
成功运行并输出了信息。[root@master ~]# kubectl logs myjob-fp4bl
hello k8s job
部署cronjob(定时任务)
范例:
编写一个CrontJob 的cron.yaml 配置文件。
任务每隔1分钟执行一次,运行的镜像时busybox,执行的命令是shell脚本,脚本执行时会爱控制台输出当前时间和字符串“hello from the kubernetes cluster”
运行yaml文件apiVersion: batch/v1beta1
kind: CronJob
metadata:
name: hello
spec:
schedule: "*/1 * * * *"
jobTemplate:
spec:
template:
spec:
containers:
- name: hello
image: busybox
args:
- /bin/sh
- -c
- date; echo Hello from the Kubernetes cluster
restartPolicy: OnFailure
查看结果[root@master ~]# kubectl create -f cron.yaml
Warning: batch/v1beta1 CronJob is deprecated in v1.21+, unavailable in v1.25+; use batch/v1 CronJob
cronjob.batch/hello created
每个一分钟会执行一次,则会出现多个pod例如[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
ds-test-crpsf 1/1 Running 0 41m
ds-test-glnql 1/1 Running 0 41m
hello-28007346-zc46p 0/1 Completed 0 43s
myjob-fp4bl 0/1 Completed 0 13m
web-statefulset-0 1/1 Running 0 63m
web-statefulset-1 1/1 Running 0 62m
web-statefulset-2 1/1 Running 0 62m
[root@master ~]# kubectl get cronjobs #查看任务情况
NAME SCHEDULE SUSPEND ACTIVE LAST SCHEDULE AGE
hello */1 * * * * False 0 37s 2m20s
[root@master ~]# kubectl logs hello-28007346-zc46p #查看日志
Sun Apr 2 13:06:17 UTC 2023
Hello from the Kubernetes cluster
hello-28007347-84nxr 0/1 Completed 0 2m32s
hello-28007348-466rq 0/1 Completed 0 92s
hello-28007349-bmx4t 0/1 Completed 0 32s
文章评论 本文章有个评论