简介

gRPC 健康探针 grpc-health-probe 是社区提供的一个工具,用来检查 gRPC 服务的健康状态,此工具 是通过 gRPC 健康检查协议公开服务的状态。

使用

我在本地使用 kratos 创建一个使用 9000 端口的 gRPC 的服务。通过 grpc-health-probe 可以检查服务的健康状态。

1
2
 grpc-health-probe -addr=localhost:9000
status: SERVING

可以看到此服务目前是健康的,不健康的服务将以非零退出代码退出。

1
2
3
grpc_health_probe -addr=localhost:9000 -connect-timeout 250ms -rpc-timeout 100ms
failed to connect service at "localhost:9000": context deadline exceeded
exit status 2

grpc_health_probe 发送了一个对 /grpc.health.v1.Health/Check 的RPC 请求。如果已 SERVING 状态作为响应,就会正常成功退出,否则会给出一个非零的退出。

Kubernetes 使用

grpc_health_probe 可用于 Kubernetes对 Pod 中运行的 gRPC 服务器进行健康检查。建议您使用Kubernetes exec探针并为您的 gRPC 服务器 pod 定义活跃度和/或就绪性检查。

您可以将静态编译grpc_health_probe的内容捆绑到您的容器映像中。

1
2
3
RUN GRPC_HEALTH_PROBE_VERSION=v0.3.1 && \
    wget -qO/bin/grpc_health_probe https://github.com/grpc-ecosystem/grpc-health-probe/releases/download/${GRPC_HEALTH_PROBE_VERSION}/grpc_health_probe-linux-amd64 && \
    chmod +x /bin/grpc_health_probe

在您的 Kubernetes Pod 规范清单中,为容器指定一个livenessProbe和/或 :readinessProbe

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
spec:
  containers:
  - name: server
    image: "[YOUR-DOCKER-IMAGE]"
    ports:
    - containerPort: 5000
    readinessProbe:
      exec:
        command: ["/bin/grpc_health_probe", "-addr=:5000"]
      initialDelaySeconds: 5
    livenessProbe:
      exec:
        command: ["/bin/grpc_health_probe", "-addr=:5000"]
      initialDelaySeconds: 10

Kubernetes v1.23 现在引入了内置的 gRPC 健康检查 功能作为 alpha 功能。因此,您可能不再需要使用此工具,而是使用原生 Kubernetes 功能。

如果您使用的是旧版本的 Kubernetes,或者使用高级配置(例如自定义元数据、TLS 或更精细的超时调整),或者根本不使用 Kubernetes,这个工具仍然很有用。

参考