likes
comments
collection
share

Pod容器频繁重启 - 关于k8s探针需要知道的几点

作者站长头像
站长
· 阅读数 4

介绍

在部署应用到k8s以后,有时会遇到pod中容器的频繁重启。这个时候,就需要检查pod的各种探针(尤其是存活探针)的配置是否合理,以及探针是否的端点(endpoint)的设置是否合理了。

本文主要是对k8s中定义的探针进行一些小结,主要是突出重点,以便在实际开发和部署时作为参考。

k8s探针小结

探针类型

按照k8s的官网,主要定义了如下3种探针:

  • Liveness Probe:如果失败,则重启容器
  • Readiness Probe:如果失败,则停止接收请求(也可能从LB中暂时移除)
  • Startup Probe:如果失败,则kill容器,然后交由pod的restartPolicy决定如何处理

一个通用模式

A common pattern for liveness probes is to use the same low-cost HTTP endpoint as for readiness probes, but with a higher failureThreshold. This ensures that the pod is observed as not-ready for some period of time before it is hard killed.

即:Liveness与Readiness探针使用同一个检查端点,但是Liveness探针的failureThreshold给一个比Readiness探针高的值。

探针检查方式

  • exec:通过命令是否返回0来判断探针是否成功

  • http:通过检查http请求返回的响应状态码来判断探针是否成功

    • 凡是在在区间[200,400)之内的都算作成功,包括redirect
  • tcp:通过检查端口是否可以连接来判断探针是否成功

    • For a TCP probe, the kubelet makes the probe connection at the node, not in the Pod, which means that you can not use a service name in the host parameter since the kubelet is unable to resolve it.
  • gRPC:通过gRPC健康检查协议来判断探针是否成功

    • 该特性在1.27才开始稳定

    • 被探测的服务必须实现gRPC的健康检查协议,即实现一个gRPC接口,如下:

      syntax = "proto3";
      
      package grpc.health.v1;
      
      message HealthCheckRequest {
        string service = 1;
      }
      
      message HealthCheckResponse {
        enum ServingStatus {
          UNKNOWN = 0;
          SERVING = 1;
          NOT_SERVING = 2;
          SERVICE_UNKNOWN = 3;  // Used only by the Watch method.
        }
        ServingStatus status = 1;
      }
      
      service Health {
        rpc Check(HealthCheckRequest) returns (HealthCheckResponse);
      
        rpc Watch(HealthCheckRequest) returns (stream HealthCheckResponse);
      }
      

Pod中的容器经常重启问题的检查思路

在Spring应用中,通常使用/actuator/health作为探针检查的端点(endpoint),而有时候会出现pod容器经常重启的情况。这个时候,要检查:

  • Liveness Probe的设置是否合理

    • 尤其是failureThreshold的设置是否合理,即:是否对异常情况由足够的容忍时间
  • Spring中的HealthIndicator的设置是否合理

    • 检查所有的HealthIndicator的bean,看是否有一些bean的健康检查过于苛刻和不合理

总结

在实际的开发部署中,遇到pod容器重启的问题,除了上述问题的排查,其实还有一个很重要的方向,局势资源的使用情况。如果k8s发现某个容器的资源已经耗尽,那么也会重启容器。