简介
Kubernetes 就绪探针是用于监控容器健康状态并确保只有完全运行的服务才能接收网络流量的重要机制。本教程提供了一份全面指南,用于理解、配置和在 Kubernetes 环境中实现就绪探针,帮助开发人员和 DevOps 专业人员创建更健壮、可靠的容器部署。
Kubernetes 就绪探针是用于监控容器健康状态并确保只有完全运行的服务才能接收网络流量的重要机制。本教程提供了一份全面指南,用于理解、配置和在 Kubernetes 环境中实现就绪探针,帮助开发人员和 DevOps 专业人员创建更健壮、可靠的容器部署。
Kubernetes 就绪探针是一种关键机制,用于确定容器是否准备好接收流量。它有助于确保只有健康的容器才会被纳入服务负载均衡,防止潜在有故障的容器接收客户端请求。
就绪探针通过定期检查应用程序的健康状态来评估容器处理请求的能力。与存活探针不同,就绪探针专门关注确定容器是否准备好处理传入流量。
探针类型 | 描述 | 常见用例 |
---|---|---|
HTTP 探针 | 发送 HTTP GET 请求 | Web 应用程序、REST API |
TCP 探针 | 检查 TCP 套接字连接 | 数据库连接、网络服务 |
Exec 探针 | 在容器内运行命令 | 自定义健康检查脚本 |
apiVersion: apps/v1
kind: Deployment
metadata:
name: web-application
spec:
template:
spec:
containers:
- name: app
image: myapp:latest
readinessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 10
periodSeconds: 5
failureThreshold: 3
在这个 Ubuntu 22.04 示例中,我们将演示一个针对 Python Flask 应用程序的简单就绪探针配置:
from flask import Flask, jsonify
import time
app = Flask(__name__)
startup_time = time.time()
@app.route('/health')
def health_check():
## 模拟应用程序预热
if time.time() - startup_time < 30:
return jsonify({"status": "initializing"}), 503
return jsonify({"status": "healthy"}), 200
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080)
此示例展示了一个就绪探针,它会在应用程序运行至少 30 秒之前阻止流量,确保在处理请求之前完成完整的启动序列。
Kubernetes 就绪探针提供了精细的配置选项,用于微调容器健康检查。精确的参数设置可确保强大的服务可靠性和优化的流量管理。
参数 | 描述 | 默认值 | 范围 |
---|---|---|---|
initialDelaySeconds | 首次探测前的延迟 | 0 | 0 - 无穷大 |
periodSeconds | 探测频率 | 10 | 1 - 无穷大 |
timeoutSeconds | 探测响应超时时间 | 1 | 1 - 无穷大 |
successThreshold | 连续成功检查次数 | 1 | 1 - 无穷大 |
failureThreshold | 连续失败检查次数 | 3 | 1 - 无穷大 |
readinessProbe:
httpGet:
path: /healthz
port: 8080
httpHeaders:
- name: Custom-Header
value: Readiness-Check
initialDelaySeconds: 15
periodSeconds: 5
timeoutSeconds: 2
successThreshold: 1
failureThreshold: 3
import socket
import time
def tcp_health_check(host, port, timeout=5):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
result = sock.connect_ex((host, port))
return result == 0
except Exception:
return False
finally:
sock.close()
## Kubernetes 探针中的示例用法
def main():
database_host = 'postgresql-service'
database_port = 5432
while True:
if tcp_health_check(database_host, database_port):
print("数据库连接成功")
else:
print("数据库连接失败")
time.sleep(10)
#!/bin/bash
## health_check.sh
## 检查数据库连接
pg_isready -h $DATABASE_HOST -p $DATABASE_PORT
## 检查特定于应用程序的条件
if [ $? -eq 0 ]; then
exit 0
else
exit 1
fi
这种全面的方法展示了多种探针配置技术,可在 Kubernetes 环境中实现精确的容器健康监控和服务可靠性。
高级探针策略能够实现比基本就绪检查更复杂的容器健康管理,纳入多维度可靠性评估和动态错误处理。
策略级别 | 特点 | 复杂程度 |
---|---|---|
基本 | 简单的 HTTP/TCP 检查 | 低 |
中级 | 自定义脚本验证 | 中 |
高级 | 多依赖项监控 | 高 |
import subprocess
import sys
import psutil
def check_system_resources():
## CPU 使用情况检查
cpu_usage = psutil.cpu_percent(interval=1)
if cpu_usage > 80:
return False
## 内存可用性检查
memory = psutil.virtual_memory()
if memory.percent > 90:
return False
return True
def check_database_connection():
try:
result = subprocess.run(
['pg_isready', '-h', 'database-host'],
capture_output=True,
text=True
)
return result.returncode == 0
except Exception:
return False
def advanced_readiness_check():
checks = [
check_system_resources(),
check_database_connection()
]
if all(checks):
print("系统完全就绪")
sys.exit(0)
else:
print("系统未就绪")
sys.exit(1)
if __name__ == "__main__":
advanced_readiness_check()
apiVersion: apps/v1
kind: Deployment
metadata:
name: complex-application
spec:
template:
spec:
containers:
- name: app
readinessProbe:
exec:
command:
- /bin/sh
- -c
- python3 /health/advanced_check.py
initialDelaySeconds: 30
periodSeconds: 10
failureThreshold: 3
#!/bin/bash
## performance_probe.sh
## 检查应用程序响应时间
RESPONSE_TIME=$(curl -o /dev/null -s -w "%{time_total}"
## 定义性能阈值
if (( $(echo "$RESPONSE_TIME > 0.5" | bc -l) )); then
echo "检测到性能下降"
exit 1
else
echo "性能在可接受范围内"
exit 0
fi
这些高级探针策略展示了复杂的容器健康管理方法,能够实现更健壮、智能的 Kubernetes 部署。
通过掌握 Kubernetes 就绪探针,你可以显著提高应用程序的可靠性和性能。这些探针提供关键的健康检查,防止潜在有故障的容器接收流量,确保只有完全运行的服务才会被纳入负载均衡。了解不同的探针类型、配置策略和实现技术将帮助你构建更具弹性和响应能力的 Kubernetes 应用程序。