k8s--重启策略

介绍

一旦容器探测出现了问题,k8s 就会对容器所在的 pod 进行重启,其实这是由 pod 的重启策略决定的,pod 的重启策略有三种,分别如下

  • Always:容器失效时,自动重启该容器,这也是默认值
  • OnFailure:容器终止运行且退出码不为 0 时重启
  • Never:不论状态为何,都不重启该容器

重启策略适应于 pod 对象中的所有容器,首次需要重启的容器,将在其需要时立即进行重启,随后需要重启的操作将由 kubelet 延迟一段时间后进行,且反复的重启操作的延迟时长依次为 10s、20s、40s、80s、160s、300s。300s 是最大延迟时长

Always

创建 pod-restartpolicy.yaml,内容如下:

apiVersion: v1
kind: Pod
metadata:
  name: pod-restartpolicy
  namespace: zouzou
spec:
  containers:
  - name: nginx
    image: nginx:1.14
    ports:
    - name: nginx-port
      containerPort: 80
    livenessProbe: # 探针,没有 /hello 的路径
      httpGet:
        scheme: HTTP
        port: 80
        path: /hello
  restartPolicy: Always # 设置重启策略,默认就为 Always

启动 pod

kubectl apply -f pod-restartpolicy.yaml

查看 pod

# 发现 pod 在重启,RESTARTS
[root@dce-10-6-215-215 tmp]# kubectl get pod pod-restartpolicy -n zouzou
NAME                READY   STATUS    RESTARTS   AGE
pod-restartpolicy   1/1     Running   2          77s

Never

上面设置了 restartPolicy: Always ,这也是默认策略,发现容器启动不了就一直在重启,我们将 restartPolicy 改为 Never,看下效果

先删除上面创建的 pod

# 删除 pod
kubectl delete pod pod-restartpolicy -n zouzou

修改 pod-restartpolicy.yaml,内容如下

apiVersion: v1
kind: Pod
metadata:
  name: pod-restartpolicy
  namespace: zouzou
spec:
  containers:
  - name: nginx
    image: nginx:1.14
    ports:
    - name: nginx-port
      containerPort: 80
    livenessProbe: # 探针,没有 /hello 的路径
      httpGet:
        scheme: HTTP
        port: 80
        path: /hello
  restartPolicy: Never # 设置重启策略,改为 Never

启动 pod

# 启动 pod
kubectl apply -f pod-restartpolicy.yaml

查看 pod 和 event

# 查看 pod,发现容器没有运行,也没有 RESTARTS
[root@dce-10-6-215-215 tmp]# kubectl get pod pod-restartpolicy -n zouzou
NAME                READY   STATUS      RESTARTS   AGE
pod-restartpolicy   0/1     Completed   0          84s

# 查看 event,发现容器存活性探测失败了,停止了容器,这是因为设置的 restartPolicy: Never
[root@dce-10-6-215-215 tmp]# kubectl describe pod pod-restartpolicy -n zouzou
Name:         pod-restartpolicy
Namespace:    zouzou
Priority:     0
Node:         dce-10-6-215-200/10.6.215.200
Start Time:   Fri, 15 Apr 2022 20:15:43 +0800
......
Events:
  Type     Reason     Age                From               Message
  ----     ------     ----               ----               -------
  Normal   Scheduled  104s               default-scheduler  Successfully assigned zouzou/pod-restartpolicy to dce-10-6-215-200
  Normal   Pulled     101s               kubelet            Container image "nginx:1.14" already present on machine
  Normal   Created    101s               kubelet            Created container nginx
  Normal   Started    100s               kubelet            Started container nginx
  Warning  Unhealthy  77s (x3 over 97s)  kubelet            Liveness probe failed: HTTP probe failed with statuscode: 404
  Normal   Killing    77s                kubelet            Stopping container nginx

 

posted @ 2022-07-19 23:01  邹邹很busy。  阅读(3267)  评论(0编辑  收藏  举报