LarryDpk
发布于 2021-04-09 / 1371 阅读
0

Kubernetes Pod中容器的Liveness、Readiness和Startup探针

1 探针的作用

Kubernetes的容器生命周期管理中,有三种探针,首先要知道,这探针是属于容器的,而不是Pod

  • 存活探针:Liveness
  • 就绪探针:Readiness
  • 启动探针:Startup

Liveness探针可以知道什么时候要重启容器,如果发现容器不健康,就会杀死并重新创建新的容器。

Readniess探针可以知道要不要访问容器,如果发现容器不健康,就不会把请求路由到该容器。

Startup探针可以知道应用程序容器什么时候启动了。 如果配置了这类探测器,就可以控制容器在启动成功后再进行存活性和就绪检查, 确保这些存活、就绪探测器不会影响应用程序的启动。 这可以用于对慢启动容器进行存活性检测,避免它们在启动运行之前就被杀掉。

2 配置示例

2.1 存活Liveness

2.1.1 命令方式

apiVersion: v1
kind: Pod
metadata:
  labels:
    test: liveness
  name: liveness-exec
spec:
  containers:
  - name: liveness
    image: k8s.gcr.io/busybox
    args:
    - /bin/sh
    - -c
    - touch /tmp/healthy; sleep 30; rm -rf /tmp/healthy; sleep 600
    livenessProbe:
      exec:
        command:
        - cat
        - /tmp/healthy
      initialDelaySeconds: 5
      periodSeconds: 5

2.1.2 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: /healthz
        port: 8080
        httpHeaders:
        - name: Custom-Header
          value: Awesome
      initialDelaySeconds: 3
      periodSeconds: 3

2.1.3 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

2.2 就绪Readiness

Liveness类似:

readinessProbe:
  exec:
    command:
    - cat
    - /tmp/healthy
  initialDelaySeconds: 5
  periodSeconds: 5

2.3 使用启动探测器保护慢启动容器

幸亏有启动探测,应用程序将会有最多 5 分钟(30 * 10 = 300s) 的时间来完成它的启动。 一旦启动探测成功一次,存活探测任务就会接管对容器的探测,对容器死锁可以快速响应。 如果启动探测一直没有成功,容器会在 300 秒后被杀死,并且根据 restartPolicy 来设置 Pod 状态。

ports:
- name: liveness-port
  containerPort: 8080
  hostPort: 8080

livenessProbe:
  httpGet:
    path: /healthz
    port: liveness-port
  failureThreshold: 1
  periodSeconds: 10

startupProbe:
  httpGet:
    path: /healthz
    port: liveness-port
  failureThreshold: 30
  periodSeconds: 10

3 Springboot应用的配置

Springboot 2.3新增了探针,具体路径如下:

存活:/actuator/health/liveness

就绪:/actuator/health/readiness

需要通过添加actuator,并通过属性配置打开对应功能:

management.endpoints.web.exposure.include="*"
management.health.livenessState.enabled=true
management.health.readinessState.enabled=true
management.endpoint.health.probes.enabled=true
management.endpoint.health.probes.show-details=always

参考:

官网Configure Liveness, Readiness and Startup Probes