Kubernetes 探针是容器健康检查的重要组件,合理配置和使用探针可以提高应用程序的可靠性。本文将介绍探针的实战指南,涵盖 Liveness Probe、Readiness Probe 的配置和高级应用,同时添加一些扩展和额外参数的说明。
1. Liveness Probe
Liveness Probe
用于确定容器是否存活。当 Liveness Probe
失败时,Kubernetes 将重启容器,以确保应用程序的健康状态。
1.1 HTTP Liveness Probe
livenessProbe:
httpGet:
path: /healthz
port: 8080
initialDelaySeconds: 3
periodSeconds: 3
failureThreshold: 3
initialDelaySeconds
表示在容器启动后等待 3 秒后开始执行首次探测。periodSeconds
表示每隔 3 秒进行一次探测。failureThreshold
表示在连续 3 次探测失败后,Kubernetes 将重启容器。
Liveness Probe
的主要作用是确保容器在运行时保持活动状态,当容器处于不健康状态时,Kubernetes 会采取自动的容器重启策略。
1.2 TCP Liveness Probe
livenessProbe:
tcpSocket:
port: 8080
initialDelaySeconds: 3
periodSeconds: 3
对于 TCP Liveness Probe,同样可以设置 initialDelaySeconds
和 periodSeconds
参数。
1.3 Exec Liveness Probe
livenessProbe:
exec:
command:
- cat
- /tmp/healthy
initialDelaySeconds: 3
periodSeconds: 3
通过 Exec Liveness Probe,执行指定的命令判断容器是否存活。在上述配置中,执行的命令是 cat /tmp/healthy
。
2. Readiness Probe
Readiness Probe
用于确定容器是否准备好接收流量。当 Readiness Probe
失败时,Kubernetes 将停止向容器发送流量。
2.1 HTTP Readiness Probe
readinessProbe:
httpGet:
path: /ready
port: 8080
initialDelaySeconds: 5
periodSeconds: 5
initialDelaySeconds
表示在容器启动后等待 5 秒后开始执行首次探测。periodSeconds
表示每隔 5 秒进行一次探测。
2.2 TCP Readiness Probe
readinessProbe:
tcpSocket:
port: 8080
initialDelaySeconds: 5
periodSeconds: 5
对于 TCP Readiness Probe,同样可以设置 initialDelaySeconds
和 periodSeconds
参数。
2.3 Exec Readiness Probe
readinessProbe:
exec:
command:
- cat
- /tmp/ready
initialDelaySeconds: 5
periodSeconds: 5
通过 Exec Readiness Probe,执行指定的命令判断容器是否准备好接收流量。在上述配置中,执行的命令是 cat /tmp/ready
。
3. 高级应用
3.1 探针超时配置
readinessProbe:
httpGet:
path: /ready
port: 8080
timeoutSeconds: 2
timeoutSeconds
表示探针在 2 秒内必须完成,否则将视为失败。
3.2 探针失败阈值
livenessProbe:
httpGet:
path: /healthz
port: 8080
failureThreshold: 3
failureThreshold
表示在连续 3 次探测失败后,Kubernetes 将重启容器。
3.3 探针初始延迟随机性
livenessProbe:
httpGet:
path: /healthz
port: 8080
initialDelaySeconds: 3
periodSeconds: 3
failureThreshold: 3
initialDelaySeconds: 5
initialDelaySeconds
在 5 秒和 8 秒之间的随机时间内开始首次探测。
4.完整案例
下面是一个完整的 YAML 示例,包括 Liveness Probe 和 Readiness Probe 的配置,以及容器的重启策略:
apiVersion: v1
kind: Pod
metadata:
name: myapp
spec:
containers:
- name: myapp-container
image: myapp-image
ports:
- containerPort: 8080
readinessProbe:
httpGet:
path: /ready
port: 8080
initialDelaySeconds: 5
periodSeconds: 5
livenessProbe:
httpGet:
path: /healthz
port: 8080
initialDelaySeconds: 3
periodSeconds: 3
failureThreshold: 3
restartPolicy: Always
在上述示例中:
readinessProbe
配置了一个 HTTP 探测器,用于判断容器是否准备好接收流量。livenessProbe
配置了一个 HTTP 探测器,用于判断容器是否存活。restartPolicy: Always
指定了容器的重启策略,即使容器正常退出,也会自动重启。
这是一个简单的例子,你可以根据你的应用需求来修改探测路径、端口、重启策略,以及其他配置。确保将上述 YAML 配置保存到一个文件(例如 pod.yaml
)中,并通过 kubectl apply -f pod.yaml
命令来创建 Pod。
通过合理配置这些参数,可以使探针更灵活地适应不同的应用场景,提高容器应用程序的可维护性和可靠性。在实际应用中,根据应用的性能和启动时间,调整这些参数以达到最佳效果。