使用Kubernetes的Startup探针避免慢启动容器被误判?

解读

在国内云原生面试中,95% 的 C# 岗位都要求“能写能调能运维”。
面试官真正想问的是:

  1. 你是否知道 .NET 6+ 容器镜像冷启动慢(JIT+AOT+Health Checks 初始化)这一客观现实;
  2. 你是否能把“慢启动”与“存活探针”解耦,避免 K8s 在容器还没准备好就反复重启;
  3. 你是否能在 C# 代码里正确暴露三种探针(startup、liveness、readiness),并给出可落地的 YAML 片段。
    答不到“C# 如何注册 Startup 探针”这一层,会被直接判定为“只背过概念”。

知识点

  1. 探针类型

    • startupProbe:K8s 1.16+ 引入,仅当成功一次后,liveness/readiness 才开始探测;失败不计入 restartPolicy。
    • livenessProbe:连续失败达到阈值,kubelet 会重启容器。
    • readinessProbe:连续失败达到阈值,Pod 被从 Service Endpoints 摘除。
  2. .NET 6+ 内置的健康检查中间件
    Microsoft.Extensions.Diagnostics.HealthChecks,可分别注册三种检查逻辑。

  3. 探针参数
    initialDelaySeconds、periodSeconds、timeoutSeconds、successThreshold、failureThreshold。
    startupProbe 通常把 periodSeconds 设得短、failureThreshold 设得大,给足“最长启动时间”。

  4. 镜像体积与启动速度
    国内常用阿里云 ACR、腾讯云 TCR,镜像拉取耗时 310 s;
    若用 mcr.microsoft.com/dotnet/aspnet:6.0-alpine,冷启动平均 2.5 s;
    若带 EF Core 迁移、HttpClient 预热、JWT 缓存,可达 15
    30 s。

  5. 版本陷阱
    K8s <1.20 的 startupProbe 有 Bug,failureThreshold 过大时可能不生效;
    国内 ACK、TKE、CCE 1.20+ 已修复,但面试时要主动说“我会先确认集群版本”。

答案

  1. C# 代码:在 Program.cs 分别注册三种健康检查
var builder = WebApplication.CreateBuilder(args);

// 1. 真正的业务就绪检查
builder.Services.AddHealthChecks()
    .AddCheck("db", () =>
    {
        using var conn = new SqlConnection(builder.Configuration.GetConnectionString("db"));
        try { conn.Open(); return HealthCheckResult.Healthy(); }
        catch { return HealthCheckResult.Unhealthy(); }
    }, tags: new[] { "ready" })
    .AddCheck("self", () => HealthCheckResult.Healthy(), tags: new[] { "live" });

var app = builder.Build();

// 2. 三条路由对应三种探针
app.MapHealthChecks("/health/startup", new HealthCheckOptions
{
    Predicate = _ => true,          // 只要进程起来就返回 200
    ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});

app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
    Predicate = check => check.Tags.Contains("ready")
});

app.MapHealthChecks("/health/live", new HealthCheckOptions
{
    Predicate = check => check.Tags.Contains("live")
});

app.Run();
  1. Dockerfile 使用单文件发布 + ReadyToRun,减少 30% 启动时间
FROM mcr.microsoft.com/dotnet/sdk:6.0-alpine AS build
WORKDIR /src
COPY . .
RUN dotnet publish -c Release -o /app -p:PublishSingleFile=true -p:PublishReadyToRun=true

FROM mcr.microsoft.com/dotnet/aspnet:6.0-alpine
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["./MyApp"]
  1. YAML:给 startupProbe 最长 120 s 的“观察窗口”,liveness/readiness 在 startup 成功后才介入
apiVersion: apps/v1
kind: Deployment
metadata:
  name: csharp-api
spec:
  replicas: 3
  selector:
    matchLabels: { app: csharp-api }
  template:
    metadata:
      labels: { app: csharp-api }
    spec:
      containers:
      - name: api
        image: registry.cn-hangzhou.aliyuncs.com/demo/csharp-api:1.0.0
        ports:
        - containerPort: 80
        startupProbe:
          httpGet:
            path: /health/startup
            port: 80
          initialDelaySeconds: 0
          periodSeconds: 5
          timeoutSeconds: 3
          successThreshold: 1
          failureThreshold: 24   # 5*24=120 s 最大容忍
        livenessProbe:
          httpGet:
            path: /health/live
            port: 80
          initialDelaySeconds: 0   # 依赖 startup 成功后才生效
          periodSeconds: 10
          timeoutSeconds: 5
          failureThreshold: 3
        readinessProbe:
          httpGet:
            path: /health/ready
            port: 80
          initialDelaySeconds: 0
          periodSeconds: 5
          timeoutSeconds: 5
          successThreshold: 1
          failureThreshold: 2
        resources:
          requests: { cpu: "100m", memory: "128Mi" }
          limits:   { cpu: "500m", memory: "512Mi" }
  1. 验证
    kubectl describe pod xxx 观察 Events:
  • 若 startupProbe 连续失败 24 次后仍未成功,Pod 会被标记为 Failed,符合预期;
  • 一旦 startupProbe 成功,liveness/readiness 才开始计数,避免误重启。

拓展思考

  1. 如果镜像里还带了 BackgroundService 做数据预热,Startup 探针应该等预热完成再返回 200,否则“假就绪”会导致第一波流量 500。
  2. 对 Serverless 场景(如阿里云 ASK、华为 CCI),冷启动可能拉到 60 s,可以把 failureThreshold 调到 60,但前提是与集群管理员沟通好,避免占用节点端口过久。
  3. 若使用 Istio,需要把 sidecar 的启动时间也纳入考量,可用 holdApplicationUntilProxyStarts 特性,或让 startupProbe 检测 sidecar 的就绪接口。
  4. 在 C# 中可结合 IHostApplicationLifetime,在 ApplicationStarted 回调里把 ManualResetEventSlim 置位,从而精确控制 /health/startup 的返回时机,实现“代码级”启动保护。