docker和k8s中如何做健康检查

3,417 阅读2分钟

docker的健康检查

docker的健康检查主要在dockerfile中,HEALTHCHECK,有两种形式:

1、禁用从基本映像继承的任何运行状况检查

FROM nginx:latest
ADD test.sh /opt/
HEALTHCHECK NONE

2、使用健康检查

FROM nginx:latest
ADD test.sh /opt/
HEALTHCHECK --interval=30s --timeout=30s --start-period=5s --retries=3 CMD [ "executable" ]
  • --interval=30s 从容器运行起来开始计时30s后开始进行健康检查,此后每隔30s进行一次健康检查

  • --timeout=30s 执行一个CMD需要的时间,如果超时则默认是错误,此后每次健康检查时间是“timeout+interval”

  • --start-period=5s 此时间进行引导的容器提供了初始化时间。在此期间内的探针故障将不计入最大重试次数。但是,如果运行状况检查在启动期间成功,则认为该容器已启动,并且所有连续失败将计入最大重试次数。

  • --retries=3 连续检查3次,都是失败,则容器不健康

命令的退出状态,映射着容器的健康状态

  • 0:容器健康,可以使用

  • 1:容器不健康,无法使用

  • 2:保留的代码,请不要使用此退出代码

k8s中的健康检查

pod健康检查

pod的健康检查主要通过两类探针

  • LivenessProbe:判断容器是否存活
  • ReadinessProbe:判断服务是否可用

实现方式分为三种

  • ExecAction:通过执行命令进行健康检查
apiVersion: v1
kind: Pod
metadata:
    name: pod-health
    lables: health
    namespaces: test
spec:
    containers:
    - name: nginx-pod
      image: nginx
      livenessProbe:
        exec:
          command:
          - cat
          - /tmp/health
        initialDelaySeconds: 80
        timeoutSeconds: 10
        periodSeconds: 5
      readinessProbe:
        httpGet:
          path: /data/health
          port: 8080
        initialDelaySeconds: 80
        timeoutSeconds: 10
        periodSeconds: 5

  • TCPSocketAction:通过IP+PORT来进行健康检查
apiVersion: v1
kind: Pod
metadata:
    name: pod-health
    lables: health
    namespaces: test
spec:
    containers:
    - name: nginx-pod
      image: nginx
      livenessProbe:
        tcpSocket:
          port: 80
        initialDelaySeconds: 80
        timeoutSeconds: 10
        periodSeconds: 5
      readinessProbe:
        httpGet:
          path: /data/health
          port: 8080
        initialDelaySeconds: 80
        timeoutSeconds: 10
        periodSeconds: 5

  • HTTPGetAction:通过容器的IP地址、端口号及路径调用来进行健康检查
apiVersion: v1
kind: Pod
metadata:
    name: pod-health
    lables: health
    namespaces: test
spec:
    containers:
    - name: nginx-pod
      image: nginx
      livenessProbe:
        httpGet:
          path: /data/health
          port: 80
        initialDelaySeconds: 80
        timeoutSeconds: 10
        periodSeconds: 5
      readinessProbe:
        httpGet:
          path: /data/health
          port: 80
        initialDelaySeconds: 80
        timeoutSeconds: 10
        periodSeconds: 5

节点健康检查

Node-Problem-Detector,它是在每个节点上运行的守护程序,可检测节点问题并将其报告给apiserver。节点问题检测器可以作为DaemonSet运行, 也可以独立运行。通过使用Event和NodeCondition将问题报告给API服务器,也可以自定义脚本、插件,让NPD定期执行检测。

参考:

https://github.com/kubernetes/node-problem-detector

https://kubernetes.io/zh/docs/tasks/debug-application-cluster/monitor-node-health/