NestJS中文文档
可靠性 / 健康检查
已译 191/191

健康检查

Terminus 集成提供就绪/存活(readiness/liveness)健康检查。健康检查在复杂的后端架构中至关重要。在 Web 开发中,健康检查通常由一个专用地址构成,例如 https://my-website.com/health/readiness。 基础设施中的某个服务或组件(例如 Kubernetes)会持续检查这个地址。根据对该地址 GET 请求返回的 HTTP 状态码,服务会在收到「不健康」响应时采取行动。 由于「健康」或「不健康」的定义随你提供的服务类型而异,Terminus 集成提供了一组健康指示器(health indicator)。

例如,如果你的 Web 服务器用 MongoDB 存数据,MongoDB 是否仍在运行就是关键信息。 这种情况下,你可以使用 MongooseHealthIndicator。配置好之后(见下文),你的健康检查地址会根据 MongoDB 是否运行返回 健康或不健康的 HTTP 状态码。

入门

开始使用 @nestjs/terminus,先安装所需依赖:

$ npm install --save @nestjs/terminus

建立健康检查

一次健康检查是若干健康指示器的汇总。健康指示器检查某个服务处于健康还是不健康状态。如果所有指定的健康指示器都正常,健康检查即为正面结果。

要建立第一个健康检查,先创建 HealthModule,并把 TerminusModule 加入它的 imports 数组。

提示

要用 Nest CLI 创建该模块,运行 $ nest g module health 命令。

health.module.ts
import { Module } from '@nestjs/common';
import { TerminusModule } from '@nestjs/terminus';

@Module({
  imports: [TerminusModule]
})
export class HealthModule {}

健康检查由控制器执行,你可以用 Nest CLI 生成它。

$ nest g controller health
提示

我们强烈建议在应用中启用关闭钩子。启用后,Terminus 集成会利用该生命周期事件报告 'shutting_down' 状态,并应用优雅关闭超时。详见应用关闭一节。

存活与就绪

安装 @nestjs/terminus、导入 TerminusModule 并创建新控制器之后,就可以创建健康检查了。

Kubernetes 这类编排器会问两个不同的问题,因此多数应用有两个健康检查:

  • 存活(liveness):进程是否已经坏了?该检查失败时,编排器重启容器。不要在这里检查依赖。重启修不好一个宕掉的数据库。
  • 就绪(readiness):应用现在能否处理请求?该检查失败时,编排器停止发送流量,直到检查再次通过。检查应用离不开的依赖。
health.controller.ts
import { Controller, Get } from '@nestjs/common';
import { HealthCheckService, FetchHealthIndicator, DiskHealthIndicator, HealthCheck } from '@nestjs/terminus';

@Controller('health')
export class HealthController {
  constructor(
    private health: HealthCheckService,
    private http: FetchHealthIndicator,
    private disk: DiskHealthIndicator,
  ) {}

  @Get('live')
  @HealthCheck()
  live() {
    return this.health.check([]);
  }

  @Get('ready')
  @HealthCheck()
  ready() {
    return this.health.check([
      () => this.http.pingCheck('payments', 'https://payments.example.com/health'),
      () => this.disk.checkStorage('storage', { path: '/', thresholdPercent: 0.9 }),
    ]);
  }
}
import { Controller, Dependencies, Get } from '@nestjs/common';
import { HealthCheckService, FetchHealthIndicator, DiskHealthIndicator, HealthCheck } from '@nestjs/terminus';

@Controller('health')
@Dependencies(HealthCheckService, FetchHealthIndicator, DiskHealthIndicator)
export class HealthController {
  constructor(health, http, disk) {
    this.health = health;
    this.http = http;
    this.disk = disk;
  }

  @Get('live')
  @HealthCheck()
  live() {
    return this.health.check([]);
  }

  @Get('ready')
  @HealthCheck()
  ready() {
    return this.health.check([
      () => this.http.pingCheck('payments', 'https://payments.example.com/health'),
      () => this.disk.checkStorage('storage', { path: '/', thresholdPercent: 0.9 }),
    ]);
  }
}

存活检查没有指示器:有应答就说明进程活着。你仍可加入只看进程自身的指示器,例如内存健康指示器。

如果支付 API 有应答且磁盘使用率低于 90%,http://localhost:3000/health/ready 处的路由会返回 下列对象,状态码 200:

{
  "status": "ok",
  "info": {
    "payments": { "status": "up", "responseTime": 87 },
    "storage": { "status": "up", "responseTime": 1 }
  },
  "error": {},
  "details": {
    "payments": { "status": "up", "responseTime": 87 },
    "storage": { "status": "up", "responseTime": 1 }
  }
}

@nestjs/terminus 包以 HealthCheckResult 导出该响应对象的类型。

status 任何健康指示器失败时,状态为 'error'。若无失败但有至少一个 'degraded',状态为 'degraded'。若 Nest 应用正在关闭但仍接受 HTTP 请求,状态为 'shutting_down'。 'error' | 'ok' | 'degraded' | 'shutting_down'
info 包含每个状态为 'up' 或 'degraded'(即「仍在服务」)的健康指示器信息。 object
error 包含每个状态为 'down'(即「不健康」)的健康指示器信息。 object
details 包含每个健康指示器的信息。 object

健康检查的状态由指示器推导:

指示器 status HTTP 状态码
全部 'up' 'ok' 200
至少一个 'degraded',没有 'down' 'degraded' 200
至少一个 'down' 'error' 503

内置健康指示器

因为许多应用需要相似的健康指示器,@nestjs/terminus 提供了一组预定义指示器:

指示器 检查什么 所需包
FetchHealthIndicator(取代已废弃的 HttpHealthIndicator) 某个 HTTP 端点有应答 无
TypeOrmHealthIndicator 数据库能应答查询 @nestjs/typeorm、typeorm
MongooseHealthIndicator 数据库能应答 ping @nestjs/mongoose、mongoose
SequelizeHealthIndicator 数据库能应答查询 @nestjs/sequelize、sequelize
MikroOrmHealthIndicator 数据库能应答查询 @mikro-orm/nestjs、@mikro-orm/core
PrismaHealthIndicator 数据库能应答查询 @prisma/client
MicroserviceHealthIndicator 微服务传输层能连上 @nestjs/microservices
GRPCHealthIndicator gRPC 服务报告 SERVING @nestjs/microservices、@grpc/grpc-js、@grpc/proto-loader
MemoryHealthIndicator 进程的内存低于上限 无
DiskHealthIndicator 磁盘占用低于上限 无

Terminus 只加载你注入的指示器所对应的包。

HTTP 健康检查

FetchHealthIndicator 用原生 fetch() 函数检查 HTTP 端点:

health.controller.ts
// 在 `HealthController` 类中

@Get()
@HealthCheck()
check() {
  return this.health.check([
    () => this.http.pingCheck('nestjs-docs', 'https://docs.nestjs.com'),
  ]);
}

如果地址在一秒内以 2xx 状态码应答,指示器为 'up'。

检查特定的 HTTP 响应码

某些情况下,你想检查特定条件并校验响应。例如,假设 https://my-external-service.com 返回 204 响应码。用 verify 选项,你可以 专门检查该响应码,并把其他所有码视为不健康。

verify 是一个函数(同步或异步),接收响应并返回布尔值,表示 它是否被视为健康(true)或不健康(false)。

health.controller.ts
// 在 `HealthController` 类中

@Get()
@HealthCheck()
check() {
  return this.health.check([
    () =>
      this.http.pingCheck('my-external-service', 'https://my-external-service.com', {
        verify: (res) => res.status === 204,
      }),
  ]);
}

如果服务以不健康的响应应答,该响应的 statusCode 与 statusText 会加入结果。

使用其他 HTTP 客户端

默认用原生 fetch() 函数发送请求。要用自己的 HTTP 客户端,请通过 fetch 选项传入函数。

用 @nestjs/http-client 时,传 request() 方法:

this.http.pingCheck('billing', 'https://billing.example.com/health', {
  fetch: this.httpClient.request,
});

该客户端在 4xx 或 5xx 响应时抛错,并默认在检查的超时内重试其中一些(例如 503)。要用 verify 检查这类响应,请把 throwOnHttpError 与 retry 设为 false:

this.http.pingCheck('billing', 'https://billing.example.com/health', {
  fetch: (url, init) => this.httpClient.request(url, { ...init, throwOnHttpError: false, retry: false }),
  verify: (res) => res.status === 503,
});

用 @nestjs/axios 时,把 Observable 转成 Promise:

this.http.pingCheck('billing', 'https://billing.example.com/health', {
  fetch: (url, init) => lastValueFrom(this.httpService.request({ url, ...init })),
});
警告

需要 @nestjs/axios 包的 HttpHealthIndicator 已废弃。请改用 FetchHealthIndicator。

TypeOrm 健康指示器

Terminus 让你把数据库检查加入健康检查。使用该健康指示器之前,请阅读 数据库一章,并确认应用的数据库连接已建立。

提示

在底层,TypeOrmHealthIndicator 执行 SELECT 1 SQL 命令,常用于验证数据库是否仍活着。对 Oracle 数据库,它使用 SELECT 1 FROM DUAL;对 SAP HANA,使用 SELECT now() FROM dummy。

把 TypeOrmHealthIndicator 注入 HealthController 并加入健康检查:

health.controller.ts
// 在 `HealthController` 类中

@Get()
@HealthCheck()
check() {
  return this.health.check([
    () => this.db.pingCheck('database').withTimeout('1s'),
  ]);
}

如果数据库可达,对 http://localhost:3000/health 的 GET 请求返回下列 JSON 结果:

{
  "status": "ok",
  "info": {
    "database": { "status": "up", "responseTime": 12 }
  },
  "error": {},
  "details": {
    "database": { "status": "up", "responseTime": 12 }
  }
}

如果你的应用使用多个数据库,请把每个 数据源注入 HealthController。然后用 connection 选项把数据源引用传给 TypeOrmHealthIndicator。

health.controller.ts
@Controller('health')
export class HealthController {
  constructor(
    private health: HealthCheckService,
    private db: TypeOrmHealthIndicator,
    @InjectDataSource('albumsConnection')
    private albumsConnection: DataSource,
    @InjectDataSource()
    private defaultConnection: DataSource,
  ) {}

  @Get()
  @HealthCheck()
  check() {
    return this.health.check([
      () => this.db.pingCheck('albums-database', { connection: this.albumsConnection }).withTimeout('1s'),
      () => this.db.pingCheck('database', { connection: this.defaultConnection }).withTimeout('1s'),
    ]);
  }
}

其他数据库指示器

其他数据库指示器的用法与 TypeOrmHealthIndicator 相同。注入指示器并加入它的检查:

this.mongoose.pingCheck('mongodb');
this.sequelize.pingCheck('database');
this.mikroOrm.pingCheck('database');
this.prisma.pingCheck('database', this.prismaClient);

磁盘健康指示器

DiskHealthIndicator 检查已使用的存储量。先注入 DiskHealthIndicator 到 HealthController。下面的例子检查路径 / 占用的存储(Windows 上用 C:\\)。 如果已用超过总空间的 50%,健康检查报告不健康状态。

health.controller.ts
// 在 `HealthController` 类中

@Get()
@HealthCheck()
check() {
  return this.health.check([
    () => this.disk.checkStorage('storage', { path: '/', thresholdPercent: 0.5 }),
  ]);
}

DiskHealthIndicator.checkStorage() 方法也可以按固定容量检查。 下面的例子在路径 / 占用的存储超过 250GB 时不健康。

health.controller.ts
// 在 `HealthController` 类中

@Get()
@HealthCheck()
check() {
  return this.health.check([
    () => this.disk.checkStorage('storage', { path: '/', threshold: '250gb' })
  ]);
}

内存健康指示器

用 MemoryHealthIndicator 确保进程不超过某个内存上限。 下面的例子检查进程的堆。

提示

堆是动态分配内存所在的区域。checkHeap() 把 process.memoryUsage() 报告的 heapUsed 值(V8 当前使用的堆内存)与给定阈值比较:字节数,或 '512kb'、'150mb'、'2gb' 这样的字符串。

health.controller.ts
// 在 `HealthController` 类中

@Get()
@HealthCheck()
check() {
  return this.health.check([
    () => this.memory.checkHeap('memory_heap', '150mb'),
  ]);
}

你也可以用 MemoryHealthIndicator.checkRSS() 检查进程的 RSS。下面的例子 在进程分配超过 150MB 时返回不健康的状态码。

提示

RSS(Resident Set Size,常驻集大小)表示分配给进程并驻留在 RAM 中的内存量。 它不包含被换出的内存。它包含共享库的内存(只要那些库的页确实在内存中), 以及所有栈与堆内存。

health.controller.ts
// 在 `HealthController` 类中

@Get()
@HealthCheck()
check() {
  return this.health.check([
    () => this.memory.checkRSS('memory_rss', '150mb'),
  ]);
}

微服务健康指示器

MicroserviceHealthIndicator 检查你的应用能否连上某个微服务传输层,例如 Redis、NATS 或 TCP。它需要 @nestjs/microservices 包与该传输层的包。

传入你为该传输层客户端使用的同一个 transport 与 options。下面的例子检查一个 Redis 服务器:

health.controller.ts
// 在 `HealthController` 类中

@Get()
@HealthCheck()
check() {
  return this.health.check([
    () =>
      this.microservice.pingCheck<RedisOptions>('redis', {
        transport: Transport.REDIS,
        options: { host: 'localhost', port: 6379 },
      }),
  ]);
}

如果连接未在一秒内建立,指示器为 'down'。

gRPC 健康指示器

GRPCHealthIndicator 检查实现了标准 gRPC 健康检查协议的 gRPC 服务。它需要 @nestjs/microservices、@grpc/grpc-js 与 @grpc/proto-loader 包。

第二个参数是要询问的服务名。如果服务在一秒内报告 SERVING,指示器为 'up'。

health.controller.ts
// 在 `HealthController` 类中

@Get()
@HealthCheck()
check() {
  return this.health.check([
    () =>
      this.grpc.checkService<GrpcOptions>('hero_service', 'hero.health.v1', {
        url: 'localhost:5000',
      }),
  ]);
}

自定义健康指示器

某些情况下,@nestjs/terminus 提供的预定义健康指示器无法覆盖你全部的健康检查需求。这时你可以创建自定义健康指示器。

多数健康指示器遵循同一模式:执行一个操作,成功则把指示器标为 'up',失败标为 'down'。HealthIndicatorService 用 attempt() 实现这个模式。为展示指示器的结构,我们创建一个示例 QueueHealthIndicator。只要 emails 队列在一秒内应答,它就是 'up' 状态。

queue.health.ts
import { InjectQueue } from '@nestjs/bullmq';
import { Injectable } from '@nestjs/common';
import { HealthIndicatorService } from '@nestjs/terminus';
import { Queue } from 'bullmq';

@Injectable()
export class QueueHealthIndicator {
  constructor(
    private readonly healthIndicatorService: HealthIndicatorService,
    @InjectQueue('emails') private readonly queue: Queue,
  ) {}

  isHealthy(key: string) {
    return this.healthIndicatorService
      .check(key)
      .attempt(() => this.queue.getWaitingCount())
      .withSuccessData((waiting) => ({ waiting }))
      .withTimeout('1s');
  }
}
import { getQueueToken } from '@nestjs/bullmq';
import { Injectable, Dependencies } from '@nestjs/common';
import { HealthIndicatorService } from '@nestjs/terminus';

@Injectable()
@Dependencies(HealthIndicatorService, getQueueToken('emails'))
export class QueueHealthIndicator {
  constructor(healthIndicatorService, queue) {
    this.healthIndicatorService = healthIndicatorService;
    this.queue = queue;
  }

  isHealthy(key) {
    return this.healthIndicatorService
      .check(key)
      .attempt(() => this.queue.getWaitingCount())
      .withSuccessData((waiting) => ({ waiting }))
      .withTimeout('1s');
  }
}

attempt() 接受同步或异步函数,并在它解析后把指示器标为 'up'。withSuccessData() 接收函数返回的值,并挑选加入结果的数据(见附加数据)。函数抛错时,指示器标为 'down',错误消息加入结果。两种情况都会把函数耗时报告为 responseTime。withTimeout() 限制这次尝试的时长(见配置检查)。

接下来,把健康指示器注册为提供者:

health.module.ts
import { BullModule } from '@nestjs/bullmq';
import { Module } from '@nestjs/common';
import { TerminusModule } from '@nestjs/terminus';
import { HealthController } from './health.controller.js';
import { QueueHealthIndicator } from './queue.health.js';

@Module({
  controllers: [HealthController],
  imports: [TerminusModule, BullModule.registerQueue({ name: 'emails' })],
  providers: [QueueHealthIndicator],
})
export class HealthModule {}

最后一步是把新的健康指示器加入健康检查端点:

health.controller.ts
import { HealthCheckService, HealthCheck } from '@nestjs/terminus';
import { Controller, Get } from '@nestjs/common';
import { QueueHealthIndicator } from './queue.health.js';

@Controller('health')
export class HealthController {
  constructor(
    private health: HealthCheckService,
    private queueHealthIndicator: QueueHealthIndicator,
  ) {}

  @Get()
  @HealthCheck()
  healthCheck() {
    return this.health.check([
      () => this.queueHealthIndicator.isHealthy('queue'),
    ]);
  }
}
import { HealthCheckService, HealthCheck } from '@nestjs/terminus';
import { Controller, Dependencies, Get } from '@nestjs/common';
import { QueueHealthIndicator } from './queue.health.js';

@Controller('health')
@Dependencies(HealthCheckService, QueueHealthIndicator)
export class HealthController {
  constructor(health, queueHealthIndicator) {
    this.health = health;
    this.queueHealthIndicator = queueHealthIndicator;
  }

  @Get()
  @HealthCheck()
  healthCheck() {
    return this.health.check([
      () => this.queueHealthIndicator.isHealthy('queue'),
    ]);
  }
}

如果队列及时应答,健康检查返回下列结果:

{
  "status": "ok",
  "info": {
    "queue": { "status": "up", "waiting": 3, "responseTime": 4 }
  },
  "error": {},
  "details": {
    "queue": { "status": "up", "waiting": 3, "responseTime": 4 }
  }
}
提示

Terminus 自己执行尝试,因此你可以把尝试直接传给 health.check([...])(this.queueHealthIndicator.isHealthy('queue')),也可以像上面的例子那样包在函数里。

用 up() 与 down() 显式控制

有时「健康」不只意味着「操作没有抛错」。要自己决定状态,请直接返回 up() 或 down(),而不是用 attempt()。下面的指示器只在缓存已连接时健康。

cache.health.ts
@Injectable()
export class CacheHealthIndicator {
  constructor(
    private readonly healthIndicatorService: HealthIndicatorService,
    private readonly cache: CacheService,
  ) {}

  async isHealthy(key: string) {
    const indicator = this.healthIndicatorService.check(key);
    const isConnected = await this.cache.isConnected();

    if (!isConnected) {
      return indicator.down('cache unreachable');
    }

    return indicator.up();
  }
}

up() 与 down() 都接受带附加数据的对象(会附加到结果),或字符串(作为 message 属性加入)。

降级状态

并非所有问题都值得让应用退出轮转。例如缓存不可达会拖慢应用,但不会让它坏掉。这类情况下,指示器可以返回 degraded()。降级的指示器不会让健康检查失败:它列在 info 下,整体状态变为 'degraded',HTTP 状态码保持 200。编排器继续路由流量,同时该状态在监控中可见。

cache.health.ts
// 在 `CacheHealthIndicator` 类中
if (!isConnected) {
  return indicator.degraded('cache unreachable, serving without cache');
}
{
  "status": "degraded",
  "info": {
    "cache": { "status": "degraded", "message": "cache unreachable, serving without cache" }
  },
  "error": {},
  "details": {
    "cache": { "status": "degraded", "message": "cache unreachable, serving without cache" }
  }
}

与 up()、down() 一样,degraded() 接受带附加数据的对象或消息字符串。一旦任何指示器为 'down',无论降级的指示器如何,整体状态都是 'error'。

警告

用 up()、down() 与 degraded() 构建的健康指示器通过返回其中之一来报告状态。这类指示器抛出的错误会被当作缺陷,而不是不健康状态:它会中止整个健康检查,导致 500 响应而不是 503。如果你的指示器包装了可能抛错的操作,请用 attempt(),它会把抛出的错误转成 'down' 状态。

配置检查

每个用 attempt() 构建的检查都返回 HealthCheckAttempt。这既包括你的自定义指示器,也包括内置指示器(已废弃的 HttpHealthIndicator 除外)。尝试执行之前,你可以通过链式调用下列方法配置它。链式顺序无关。

每个时间值接受毫秒数,或 '200ms'、'2s'、'15m' 这样的字符串。

超时

withTimeout() 限制这次尝试的时长。时间一到,指示器标为 'down',你的函数作为参数 signal 属性接收的 AbortSignal 被中止。请把该 signal 传给底层操作(例如 fetch()),让它也被取消,而不是在后台滞留。

health.controller.ts
// 在 `HealthController` 类中
@Get()
@HealthCheck()
check() {
  return this.health.check([
    () => this.db.pingCheck('database').withTimeout('1.5s'),
    () => this.queueHealthIndicator.isHealthy('queue'),
  ]);
}

如果自定义指示器中的队列未在一秒内应答,健康检查返回下列结果:

{
  "status": "error",
  "info": {
    "database": { "status": "up", "responseTime": 12 }
  },
  "error": {
    "queue": { "status": "down", "message": "timeout of 1000ms exceeded", "responseTime": 1001 }
  },
  "details": {
    "database": { "status": "up", "responseTime": 12 },
    "queue": { "status": "down", "message": "timeout of 1000ms exceeded", "responseTime": 1001 }
  }
}
警告

内置数据库、微服务与 gRPC 指示器的 timeout 选项(例如 this.db.pingCheck('database', { timeout: 1500 }))已废弃。请改为在返回的尝试上链式调用 .withTimeout()。

缓存

编排器通常每隔几秒轮询健康检查,有些检查太贵,不宜每次都跑。cacheFor() 把一次尝试的结果缓存给定时间。存在新鲜结果时,函数不再执行,并发的健康检查共享同一次在途执行。缓存跨请求共享,按指示器 key 索引。

health.controller.ts
// 在 `HealthController` 类中
@Get()
@HealthCheck()
check() {
  return this.health.check([
    () => this.db.pingCheck('database').withTimeout('1.5s').cacheFor('5s'),
  ]);
}

来自缓存的结果带 cachedResponse: true:

{
  "status": "ok",
  "info": {
    "database": { "status": "up", "responseTime": 12, "cachedResponse": true }
  },
  "error": {},
  "details": {
    "database": { "status": "up", "responseTime": 12, "cachedResponse": true }
  }
}

慢检查

仍然应答但很慢的依赖不是 'down'。degradedAfter() 在尝试成功但耗时达到给定时间时,把它标为 'degraded' 而不是 'up'。与 withTimeout() 组合,可以决定何时慢变成 'down'。

health.controller.ts
// 在 `HealthController` 类中
@Get()
@HealthCheck()
check() {
  return this.health.check([
    // < 200ms:up,200-1000ms:degraded,> 1000ms:down
    () => this.db.pingCheck('database').degradedAfter('200ms').withTimeout('1s'),
  ]);
}

如果数据库在 800 毫秒后应答,健康检查仍返回状态码 200,但报告的 'degraded' 状态(见降级状态):

{
  "status": "degraded",
  "info": {
    "database": { "status": "degraded", "responseTime": 800 }
  },
  "error": {},
  "details": {
    "database": { "status": "degraded", "responseTime": 800 }
  }
}

非关键检查

有些依赖不是处理请求所必需的。例如 emails 队列不可达时,邮件稍后发送,应用仍能工作。你希望在健康检查中看到问题,但编排器不应让应用退出轮转。degradedOnFailure() 把失败的尝试标为 'degraded' 而不是 'down'。这适用于抛出的错误与超时。错误消息仍留在结果中。

health.controller.ts
// 在 `HealthController` 类中
@Get()
@HealthCheck()
check() {
  return this.health.check([
    () => this.db.pingCheck('database').withTimeout('1.5s'),
    () => this.queueHealthIndicator.isHealthy('queue').degradedOnFailure(),
  ]);
}

如果队列未及时应答,健康检查返回状态码 200 与下列结果:

{
  "status": "degraded",
  "info": {
    "database": { "status": "up", "responseTime": 12 },
    "queue": { "status": "degraded", "message": "timeout of 1000ms exceeded", "responseTime": 1001 }
  },
  "error": {},
  "details": {
    "database": { "status": "up", "responseTime": 12 },
    "queue": { "status": "degraded", "message": "timeout of 1000ms exceeded", "responseTime": 1001 }
  }
}

你可以在同一次尝试上组合两个方法。慢的尝试与失败的尝试随后都是 'degraded';只有失败的那个有 message。

附加数据

三个方法把你自己数据加入检查结果:

  • withData() 给每个结果加静态数据,例如负责某个依赖的团队。
  • withSuccessData() 在检查成功时,从尝试函数返回的值中挑选数据。
  • withFailureData() 在检查失败时,从错误中挑选数据。
this.healthIndicatorService
  .check('payments')
  .attempt(() => this.payments.ping())
  .withData({ owner: 'team-billing' })
  .withSuccessData((result) => ({ region: result.region }))
  .withFailureData((error) => ({ code: (error as PaymentError).code }));

如果支付服务拒绝连接,结果如下:

{
  "status": "error",
  "info": {},
  "error": {
    "payments": { "status": "down", "message": "connect ECONNREFUSED 10.0.0.7:443", "owner": "team-billing", "code": "ECONNREFUSED", "responseTime": 4 }
  },
  "details": {
    "payments": { "status": "down", "message": "connect ECONNREFUSED 10.0.0.7:443", "owner": "team-billing", "code": "ECONNREFUSED", "responseTime": 4 }
  }
}

withSuccessData() 与 withFailureData() 接受同步或异步函数,或对象。这些方法也适用于内置指示器,例如 this.db.pingCheck('database').withData({ owner: 'team-billing' })。

添加数据时请记住:

  • 对同一方法的多次调用会合并,最后一个生效。
  • status、responseTime 与 cachedResponse 三个键由 Terminus 保留。你的数据中这些键会被忽略,并每个指示器记录一次警告。

日志

默认情况下,健康检查失败时 Terminus 记录错误。配置了优雅关闭超时时,它还会记录关闭进度。TerminusModule.forRoot() 方法让你更好地控制错误如何记录,也让你完全接管日志。

本节带你创建一个自定义日志器 TerminusLogger。它继承内置 ConsoleLogger, 因此你可以选择覆盖日志器的哪些部分。

提示

要了解 Nest 中自定义日志器的更多内容,见注入自定义日志器。

terminus-logger.service.ts
import { Injectable, Scope, ConsoleLogger } from '@nestjs/common';

@Injectable({ scope: Scope.TRANSIENT })
export class TerminusLogger extends ConsoleLogger {
  error(message: any, stack?: string, context?: string): void;
  error(message: any, ...optionalParams: any[]): void;
  error(
    message: unknown,
    stack?: unknown,
    context?: unknown,
    ...rest: unknown[]
  ): void {
    // 在这里覆盖错误消息的记录方式
  }
}

创建自定义日志器之后,把它传给 TerminusModule.forRoot():

health.module.ts
@Module({
imports: [
  TerminusModule.forRoot({
    logger: TerminusLogger,
  }),
],
})
export class HealthModule {}

要抑制 Terminus 的所有日志(包括错误消息),把 logger 选项设为 false:

health.module.ts
@Module({
imports: [
  TerminusModule.forRoot({
    logger: false,
  }),
],
})
export class HealthModule {}

你也可以配置健康检查错误在日志中的展示方式。

错误日志样式 说明 示例
json(默认) 检查失败时,把健康检查结果的摘要以 JSON 对象打印
pretty 检查失败时,把健康检查结果的摘要以带格式的方框打印,突出成功与失败的结果

要改变日志样式,使用 errorLogStyle 配置选项:

health.module.ts
@Module({
  imports: [
    TerminusModule.forRoot({
      errorLogStyle: 'pretty',
    }),
  ]
})
export class HealthModule {}

优雅关闭超时

如果你的应用需要推迟关闭,Terminus 可以用 gracefulShutdownTimeoutMs 选项替你处理(毫秒,默认 0)。 该设置在与 Kubernetes 这类编排器配合时特别有用。 把延迟设得略长于就绪检查间隔,就能在关闭容器时实现零停机:一旦收到终止信号,健康检查立即以 503 状态码报告 'shutting_down',于是编排器停止路由新流量,而应用在延迟期间完成在途请求。

health.module.ts
@Module({
  imports: [
    TerminusModule.forRoot({
      gracefulShutdownTimeoutMs: 1000,
    }),
  ]
})
export class HealthModule {}
警告

该延迟只对 SIGTERM 生效,这是 Kubernetes 这类编排器停止容器时发送的信号。其他信号(例如 Ctrl+C 的 SIGINT)仍会把健康检查切到 'shutting_down',但会立刻关闭应用。请确保关闭钩子已启用;否则 Terminus 永远收不到该信号。

Swagger 文档

如果安装了 @nestjs/swagger 包,@HealthCheck() 装饰器会为你记录该端点。它描述 200 与 503 响应,并注册所有健康检查端点共享的两个 schema:TerminusHealthCheckResult 与 TerminusHealthIndicatorResult。

要为某个端点关闭文档,把 swaggerDocumentation 选项设为 false:

health.controller.ts
// 在 `HealthController` 类中
@Get()
@HealthCheck({ swaggerDocumentation: false })
check() {
  return this.health.check([]);
}

打包

Terminus 用 import() 加载可选的对等依赖(例如 @nestjs/typeorm 或 @nestjs/mongoose),以便打包器能包含它们。如果你的构建把 node_modules 保持为外部依赖(Nest CLI 的默认行为),你什么都不用做。

如果你把应用与其依赖一起打包,打包器也会寻找你未安装的可选对等依赖,构建就会失败。请把这些包标记为外部依赖。例如用 esbuild:

await build({
  entryPoints: ['dist/main.js'],
  bundle: true,
  platform: 'node',
  external: ['@nestjs/mongoose', '@nestjs/sequelize', '@mikro-orm/core'],
});

用 webpack 或 Rspack 时,使用 externals 选项或 IgnorePlugin。Rollup、Rolldown 与 Vite 默认把无法解析的包保持为外部依赖。

@nestjs/swagger 包是例外:Terminus 用 require() 加载它,而只有 webpack 会跟进这种加载。用其他打包器时,请把 @nestjs/swagger 保持为外部依赖,否则健康检查端点会从 Swagger 文档中消失。用 esbuild 构建的 CommonJS 包(platform: 'node' 的默认输出)中也会消失,因为 Terminus 在那里无法加载该包。

测试

要测试应用如何报告失败的依赖,在端到端测试中替换指示器:

const moduleRef = await Test.createTestingModule({ imports: [AppModule] })
  .overrideProvider(QueueHealthIndicator)
  .useValue({
    isHealthy: () => ({ queue: { status: 'down', message: 'queue unreachable' } }),
  })
  .compile();

const app = moduleRef.createNestApplication();
await app.init();

await request(app.getHttpServer()).get('/health').expect(503);
提示

@nestjs/terminus 以 ES 模块发布。若你的测试跑在 Jest 上,见迁移指南。

可观测性

健康检查为编排器回答一个问题:这个实例该不该拿到流量?它不会告诉你上次部署后哪个路由变慢了,也不会告诉你就绪探针失败的实例当时在忙什么。NestJS Observe(我们的官方可观测性平台)记录其余部分——请求、任务、错误、查询与追踪,以及在每个实例内部采样的 CPU、内存与事件循环延迟——其中两个设置与本章的检查配合使用。

探针每隔几秒调用健康端点,留在指标里会把真实流量淹没在请求指标中。请用 SDK 的 http.ignore 选项把它们排除(见忽略噪音操作):

app.module.ts
ObserveModule.forRoot({
  // ...
  http: { ignore: ['/health'] },
});

通过的存活检查也不代表有任何东西在被服务。对于全天候运行的应用,内置告警会在它安静下来或错误率异常时给你发邮件,所有套餐(含免费版)都有。见可观测性一章。

更多示例

kitchen sink 示例是一个小应用,组合了本章的大部分内容:存活与就绪检查、内置与自定义健康指示器、'degraded' 状态,以及测试。它不需要数据库。

更多可运行示例(每个内置健康指示器一个)见 Terminus 示例目录。