k8s健康检查(探针Probe)之LivenessProbe、ReadinessProbe和StartupProbe

背景

集群正常服务时,会出现容器死掉问题,如宿主机故障、资源不足、下游故障等。这个时候容器需要从endpoints摘除(容器挂了就不能接流了),并执行它的restart策略。

LivenessProbe、ReadinessProbe和StartupProbe可以比较优雅地解决这类问题。

简介

官方文档https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/
有3种方式进行探测服务或容器是否正常:执行脚本、tcp端口探活、http探活
这3种方式并不是互斥的,结合使用效果更佳。

LivenessProbe探针

作用:当探测失败,Liveness策略将会重建或者漂移该容器。

适用场景:容器跑着跑着可能就挂了,比如宿主机故障,这时候需要漂移这台容器。

ReadinessProbe(就绪探针)

作用:当探测失败,说明容器未就绪,Readiness策略会把容器从Endpoints中移除。

StartupProbe(启动探针)

作用

如果提供了Startup的探针,则先禁用其他探针,直到StartupProbe探测到服务正常启动了才启用其他探针。如果探测失败,容器将会通过restart策略进行重启。

适用场景

这主要为了解决部分服务启动缓慢的问题,在这服务启动之前,很容易被Liveness探针和Readiness探针误判为服务挂了。

startupProbe是在k8s v1.16加入了alpha版,官方对其作用的解释是:

Indicates whether the application within the Container is started. All other probes are disabled if a startup probe is provided, until it succeeds. If the startup probe fails, the kubelet kills the Container, and the Container is subjected to its restart policy. If a Container does not provide a startup probe, the default state is Success
大概是意思是:判断容器内的应用程序是否已启动。如果提供了启动探测,则禁用所有其他探测,直到它成功为止。如果启动探测失败,kubelet将杀死容器,容器将服从其重启策略。如果容器没有提供启动探测,则默认状态为成功。

探测方式

有3种方式进行探测服务或容器是否正常:exec执行命令、tcp端口探活、http探活
参数解释:

  • initialDelaySeconds:在第一次探测之前应该等待的时间。
  • periodSeconds:两次探测之间的时间间隔。

exec执行命令

apiVersion: v1
kind: Pod
metadata:
  labels:
    test: liveness
  name: liveness-exec
spec:
  containers:
  - name: liveness
    image: k8s.gcr.io/busybox
    livenessProbe:
      exec:
        command:
        - cat
        - /tmp/healthy
      initialDelaySeconds: 5
      periodSeconds: 5

解释:

  • 通过执行命令cat /tmp/healthy来探测。
  • initialDelaySeconds参数说明,在第一次探测之前应该等待5s。
  • periodSeconds参数说明:两次探测之间的间隔为5s。

http方式

apiVersion: v1
kind: Pod
metadata:
  labels:
    test: liveness
  name: liveness-http
spec:
  containers:
  - name: liveness
    image: k8s.gcr.io/liveness
    args:
    - /server
    livenessProbe:
      httpGet:
        path: /health
        port: 8080
        httpHeaders:
        - name: aaaaa
          value: bbbbb
      initialDelaySeconds: 3
      periodSeconds: 3

解释:

  • 通过访问容器的8080端口、/health接口进行健康检查。
  • httpHeaders参数指明请求头。
  • initialDelaySeconds参数说明,在第一次探测之前应该等待5s。
  • periodSeconds参数说明:两次探测之间的间隔为5s。

TCP方式

apiVersion: v1
kind: Pod
metadata:
  name: goproxy
  labels:
    app: goproxy
spec:
  containers:
  - name: goproxy
    image: k8s.gcr.io/goproxy:0.1
    ports:
    - containerPort: 8080
    readinessProbe:
      tcpSocket:
        port: 8080
      initialDelaySeconds: 5
      periodSeconds: 10
    livenessProbe:
      tcpSocket:
        port: 8080
      initialDelaySeconds: 15
      periodSeconds: 20

解释:

  • 此处对8080端口进行探活。
  • 可以看到,这里既用了readinessProbe也用了livenessProbe。

FAQ

健康检查是由谁发起的?

  • http请求是由k8s发起的,访问pod的ip。




参考文档:



京城郭少

posted @ 2021-10-23 16:53  NetRookieX  阅读(138)  评论(0编辑  收藏  举报