Skip to content

配置 Kubernetes Health 检查

中等 约 25 分钟

你将构建什么

Kubernetes 部署使用 properly 配置 liveness and readiness probes 那个 ensure application 是 healthy and ready 之前接收 traffic.

学习目标

  • 理解 difference 之间 liveness and readiness probes
  • 配置 liveness probe 到启用 self-healing
  • 配置 readiness probe 到 control traffic routing
  • 测试 probe behavior 通过 simulating failures

前置要求

  • Kubernetes cluster 使用 kubectl
  • application 使用 /health and /ready 端点
  • 基础理解的 Kubernetes 部署

步骤

  1. 1

    添加 readiness probe

    添加 readiness probe 到你的容器 spec. 这个 probe 检查如果 application 是 ready 到 serve traffic. Pod 将不 接收 traffic 直到这个 probe succeeds.

    代码
    readinessProbe:
      httpGet:
        path: /ready
        port: 8080
      initialDelaySeconds: 5
      periodSeconds: 10
      failureThreshold: 3

    预期结果

    Pod 做不 接收 traffic 直到 /ready 返回 200.

  2. 2

    添加 liveness probe

    添加 liveness probe 到检查如果 application 是 still healthy. 如果这个 probe 失败, Kubernetes restarts 容器.

    代码
    livenessProbe:
      httpGet:
        path: /health
        port: 8080
      initialDelaySeconds: 15
      periodSeconds: 20
      failureThreshold: 3

    预期结果

    如果 /health 失败 3 次数, Kubernetes restarts 容器.

  3. 3

    部署 and 验证

    Apply 部署 and watch Pods. 它们应该开始, wait for readiness, 然后 become ready and 开始接收 traffic.

    代码
    kubectl apply -f deployment.yaml
    kubectl get pods -w  # watch pod status

    预期结果

    Pods go 从运行到 Ready 之后 readiness probe succeeds.

  4. 4

    测试 probe 失败

    Simulate 失败通过制作 /health 端点返回错误. Watch Kubernetes 重启容器之后 liveness probe 失败.

    代码
    # Simulate failure (e.g., kubectl exec to break the endpoint)
    # Then watch Kubernetes restart the Pod
    kubectl get pods -w

    预期结果

    之后 3 失败 liveness 检查, Kubernetes kills and restarts 容器.

  5. 5

    添加健康检查端点

    为应用添加 /health 端点返回 200 OK,供编排系统(Kubernetes、负载均衡器)探测存活。健康检查是生产部署的基础设施。

    代码
    # app.py (Flask example)
    from flask import Flask, jsonify
    app = Flask(__name__)
    
    @app.route("/health")
    def health():
        return jsonify({"status": "ok"}), 200
    
    @app.route("/ready")
    def ready():
        # Check DB connection etc.
        return jsonify({"ready": True}), 200

    预期结果

    curl localhost:5000/health 返回 {"status":"ok"} 和 200 状态码。

自己动手试试

你学到了什么

你配置 liveness and readiness probes for self-healing and safe traffic routing. Probes 是必要 for reliable Kubernetes 部署 — 它们 let cluster know 当到 重启 or 停止 routing 到你的 application.

相关资源

相关术语

相关术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回主题