Nest集成健康检查
文章目录
- 前言
- ✅ NestJS 健康检查集成思路(标准实践)
- 📦 推荐使用官方包:
- 🧱 结构设计
- ✅ 1. 创建健康模块
- ✅ 2. 集成 `@nestjs/terminus`
- `health.module.ts`
- `health.controller.ts`
- ✅ 3. 在 AppModule 注册模块
- 🔍 支持的指标组件(可选引入)
- 📋 典型输出格式(符合 Kubernetes 要求):
- 💡 增强建议
前言
健康检查(Health Check)是服务治理的基础能力,主要用于让运维平台、K8s、负载均衡、监控系统等自动探测你的服务是否健康可用,并在服务异常时自动重启、摘除或告警。
- 核心思路
暴露一个健康检查接口(如 /health、/actuator/health),外部系统定时访问。
接口返回服务健康状态(如 200 OK + 简明 JSON)。
检查内容可扩展:不仅仅是进程存活,还可以检测数据库、缓存、外部依赖、磁盘空间等。
在NestJS 项目中,健康检查(Health Check)模块是必须集成的组件,尤其是部署在 Kubernetes、ECS、容器平台或对接服务网关时,便于实现:
- 存活探针(liveness)
- 就绪探针(readiness)
- 服务自我诊断(数据库、缓存、第三方接口)
- Prometheus 状态采集
✅ NestJS 健康检查集成思路(标准实践)
📦 推荐使用官方包:
pnpm add @nestjs/terminus
🧱 结构设计
✅ 1. 创建健康模块
nest g module health
nest g controller health
✅ 2. 集成 @nestjs/terminus
health.module.ts
import { Module } from '@nestjs/common';
import { TerminusModule } from '@nestjs/terminus';
import { HealthController } from './health.controller';@Module({imports: [TerminusModule],controllers: [HealthController],
})
export class HealthModule {}
health.controller.ts
import {Controller,Get,
} from '@nestjs/common';
import {HealthCheckService,HttpHealthIndicator,TypeOrmHealthIndicator,HealthCheck,
} from '@nestjs/terminus';@Controller('health')
export class HealthController {constructor(private health: HealthCheckService,private http: HttpHealthIndicator,private db: TypeOrmHealthIndicator, // 或 MongooseHealthIndicator、PrismaHealthIndicator) {}@Get()@HealthCheck()check() {return this.health.check([() => this.http.pingCheck('nestjs-docs', 'https://docs.nestjs.com'),() => this.db.pingCheck('database'),]);}
}
// src/health/health.service.ts
import { Injectable, Inject } from '@nestjs/common';
import {HealthIndicatorResult,HealthCheckError,
} from '@nestjs/terminus';
import { Logger } from 'winston';
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';
import Redis from 'ioredis';
import { DingTalkHelper } from '../utils/ding.helper';
import { PrismaService } from '../prisma/prisma.service';
import DailyRotateFile from 'winston-daily-rotate-file';@Injectable()
export class HealthIndicatorService {constructor(private readonly prisma: PrismaService,@Inject('REDIS_CLIENT') private redisClient: Redis,@Inject(WINSTON_MODULE_NEST_PROVIDER)private readonly logger: Logger,) {}async checkDb(): Promise<HealthIndicatorResult> {try {await this.prisma.$queryRaw`SELECT 1`;return { database: { status: 'up' } };} catch (e) {this.logger.error('[HealthCheck] Prisma DB down', e);await DingTalkHelper.alert('🔴Prisma数据库连接失败');throw new HealthCheckError('Prisma DB failed', e);}}async checkRedis(): Promise<HealthIndicatorResult> {try {await this.redisClient.ping();return { redis: { status: 'up' } };} catch (e) {this.logger.error('[HealthCheck] Redis down', e);await DingTalkHelper.alert('🟠Redis连接失败');throw new HealthCheckError('Redis failed', e);}}
}
✅ 3. 在 AppModule 注册模块
@Module({imports: [HealthModule,// your other modules],
})
export class AppModule {}
🔍 支持的指标组件(可选引入)
指标组件 | 描述 |
---|---|
HttpHealthIndicator | 检查第三方 HTTP 是否通 |
TypeOrmHealthIndicator | 检查数据库连接 |
MongooseHealthIndicator | 检查 MongoDB |
RedisHealthIndicator | 检查 Redis 连接 |
GRPCHealthIndicator | 检查 gRPC 服务 |
📋 典型输出格式(符合 Kubernetes 要求):
{"status": "ok","info": {"nestjs-docs": { "status": "up" },"database": { "status": "up" }},"error": {},"details": {"nestjs-docs": { "status": "up" },"database": { "status": "up" }}
}
💡 增强建议
项目 | 推荐实践 |
---|---|
🚦 readiness 与 liveness 分开路径 | /health/live , /health/ready |
📈 Prometheus Export | 可接入 @willsoto/nestjs-prometheus 或定制 exporter |
🔐 授权保护 | 可为健康检查加入白名单机制或 token 认证 |
🧪 异常告警机制 | health 状态为 down 时自动告警或推送 |
🧰 集成 log/tracing | 在健康检查中也记录 traceId 或日志 |