-
首先创建一个yaml,创建一个名字是busybox-test的容器
apiVersion: v1
kind: Pod
metadata:
name: busybox-test
labels:
purpose: demonstrate-busybox
spec:
containers:
- name: busybox
image: busybox
imagePullPolicy: IfNotPresent
command:
- sleep
- "3600"
resources:
limits:
memory: "128Mi"
cpu: "500m" -
然后拉取busybox的安装镜像(如果可以连上docker仓库则可以不需要下载)
sudo docker pull busybox sudo docker save busybox -o busybox.tar
-
加载busybox镜像
sudo ctr -n k8s.io images import busybox.tar
-
然后根据yaml启动busybox pod
kubectl apply -f cronjob.yaml
-
此时busybox的pod已经运行起来了
$ kubectl get pods
NAME READY STATUS RESTARTS AGE
busybox-test 1/1 Running 0 7m10s
helloworld-nodejs-78c85f6bc8-kvrw6 1/1 Running 1 (5h15m ago) 3d5h
helloworld-nodejs-78c85f6bc8-l9mxg 1/1 Running 1 (5h15m ago) 3d5h
nginx-deployment-54b6f7ddf9-vcl6k 1/1 Running 3 (5h15m ago) 6d22h
nginx-deployment-54b6f7ddf9-x6j7z 1/1 Running 3 (5h15m ago) 6d22h -
可以进pod中执行一些命令
$ kubectl exec -it busybox-test -- sh
/ # ps aux
PID USER TIME COMMAND
1 root 0:00 sleep 3600
20 root 0:00 sh
26 root 0:00 ps aux
然后可以将它拓展为一个cronjob的pod,定时运行,yaml改写成:
apiVersion: batch/v1
kind: CronJob
metadata:
name: example-cronjob
spec:
schedule: "*/1 * * * *"
jobTemplate:
spec:
template:
spec:
containers:
- name: example-container
image: busybox
imagePullPolicy: IfNotPresent
args:
- /bin/sh
- -c
- date; echo Hello from the Kubernetes cluster
restartPolicy: OnFailure
这个yaml的意思就是创建一个cronjob,然后每1分钟(schedule: "*/1 * * * *")会创建一个busybox的pod执行"/bin/sh -c date; echo Hello from the Kubernetes cluster" 命令
-
可以通过下面命令看到cronjob的pods已经创建起来了
$ kubectl get pods
NAME READY STATUS RESTARTS AGE
example-cronjob-28659390-fk9kq 0/1 Completed 0 2m15s
example-cronjob-28659391-gbkps 0/1 Completed 0 75s
example-cronjob-28659392-sxzzg 0/1 Completed 0 15s
helloworld-nodejs-78c85f6bc8-kvrw6 1/1 Running 1 (5h29m ago) 3d5h
helloworld-nodejs-78c85f6bc8-l9mxg 1/1 Running 1 (5h29m ago) 3d5h
nginx-deployment-54b6f7ddf9-vcl6k 1/1 Running 3 (5h29m ago) 6d23h
nginx-deployment-54b6f7ddf9-x6j7z 1/1 Running 3 (5h29m ago) 6d23h$ kubectl get cronjobs
NAME SCHEDULE SUSPEND ACTIVE LAST SCHEDULE AGE
example-cronjob */1 * * * * False 0 10s 8m22s$ kubectl get jobs
NAME COMPLETIONS DURATION AGE
example-cronjob-28659393 1/1 3s 2m38s
example-cronjob-28659394 1/1 3s 98s
example-cronjob-28659395 1/1 3s 38s -
查看cronjob的输出, 可以看到yaml里面配置的内容:
$ kubectl logs example-cronjob-28659396-mklws
Fri Jun 28 08:36:00 UTC 2024
Hello from the Kubernetes cluster -
删除cronjob
$ kubectl delete cronjobs example-cronjob
cronjob.batch "example-cronjob" deleted