如何在docker容器cron作业中运行kubectl命令



1.kubectl命令在容器终端中给出响应并获取集群信息。

[root@cronjob-cj-m1dr3tsda-aw5rv /]# kubectl cluster-info
Kubernetes control plane is running at https://172.20.0.1:443
CoreDNS is running at https://172.20.0.1:443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy

2.我们在容器中运行了crontab,并在crontab中安排了一些作业,如下所示

*/30 * * * * root /usr/local/bin/scheduler_job.sh >> /var/log/scheduler_job.log
cat scheduler_job.sh
#!/bin/bash
whereis kubectl
kubectl version --client
kubectl cluster-info
kubectl get pods -n kube-system
kubectl rollout restart ds/scheduler-ds -n kube-system
Above kubectl commands output is empty
kubectl: /usr/local/bin/kubectl
Tue Dec 20 11:05:04 UTC 2022
WARNING: This version information is deprecated and will be replaced with the output from kubectl version --short.  Use --output=yaml|json to get the full version.
Client Version: version.Info{Major:"1", Minor:"26", GitVersion:"v1.26.0", GitCommit:"b46a3f887ca979b1a5d14fd39cb1af43e7e5d12d", GitTreeState:"clean", BuildDate:"2022-12-08T19:58:30Z", GoVersion:"go1.19.4", Compiler:"gc", Platform:"linux/amd64"}
Kustomize Version: v4.5.7

Crontab调度作业脚本有kubectl命令,其输出为空,请帮助我们如何配置以获得对容器内运行的Crontab计划作业的集群访问?

运行kubectl命令的容器不能使用默认服务帐户。您需要创建一个特定的。

这里有一个很好的方法:https://itnext.io/running-kubectl-commands-from-within-a-pod-b303e8176088

但每30分钟重新部署一次在我看来是众所周知的。如果遇到内存或cpu问题,请考虑在sour部署中添加resources部分。

类似的东西:

spec:
containers:
- name: app
image: images.my-company.example/app:v4
resources:
requests:
memory: "64Mi"
cpu: "250m"
limits:
memory: "128Mi"
cpu: "1500m"

根据您的需求,如果您还没有,也可以使用livenssProbe。

有一个解决此问题的方法,您可以尝试将kubernetes作业与kubernete调度器一起使用,以便在pod中以所需的时间间隔执行命令,甚至可以在特定事件发生时触发这些作业。

最新更新