Tiếp tục với series, bài này mình sẽ giới thiệu với mọi người về health check với Terminus trong NestJS: một địa chỉ để Docker, Kubernetes hay load balancer hỏi TaskFlow API còn sống không, đã sẵn sàng nhận request chưa.
1. Health check và Terminus.
Health check là route (thường là /health) trả 200 khi ứng dụng khoẻ, 503 khi có vấn đề. Có hai loại:
- Liveness: process còn chạy bình thường không. Lỗi thì container bị khởi động lại, nên không kiểm tra database ở đây.
- Readiness: đã sẵn sàng nhận request chưa (kết nối được database...). Lỗi thì load balancer tạm ngừng gửi request tới instance đó.
@nestjs/terminus là package health check chính thức của NestJS, có sẵn các health indicator cho Prisma, Mongoose, ổ đĩa, bộ nhớ... Mình cài nó (bản 12.1.0):
npm install @nestjs/terminus
nest g module health --format
nest g controller health --no-spec --format
- src/health/health.module.ts (RedisHealthIndicator viết ở phần 3)
import { Module } from '@nestjs/common';
import { TerminusModule } from '@nestjs/terminus';
import { HealthController } from './health.controller.js';
import { RedisHealthIndicator } from './redis.health.js';
@Module({
imports: [TerminusModule],
controllers: [HealthController],
providers: [RedisHealthIndicator],
})
export class HealthModule {}
2. Kiểm tra database, ổ đĩa và bộ nhớ.
Mỗi check là một hàm gọi indicator, HealthCheckService.check() chạy song song và gộp kết quả:
- src/health/health.controller.ts (phần đầu, checkDisk() ở phần 3, phần còn lại ở phần 4)
import {
Controller,
Get,
Res,
ServiceUnavailableException,
VERSION_NEUTRAL,
} from '@nestjs/common';
import {
DiskHealthIndicator,
HealthCheck,
HealthCheckService,
type HealthCheckResult,
type HealthIndicatorFunction,
HealthIndicatorService,
MemoryHealthIndicator,
MongooseHealthIndicator,
PrismaHealthIndicator,
} from '@nestjs/terminus';
import type { Response } from 'express';
import { Roles } from '../auth/roles.decorator.js';
import { Public } from '../common/decorators/public.decorator.js';
import { PrismaService } from '../prisma/prisma.service.js';
import { RedisHealthIndicator } from './redis.health.js';
// VERSION_NEUTRAL: đường dẫn không có /v1, cùng với exclude ở app.setup.ts -> /health/...
@Controller({ path: 'health', version: VERSION_NEUTRAL })
export class HealthController {
constructor(
private readonly health: HealthCheckService,
private readonly prismaHealth: PrismaHealthIndicator,
private readonly prisma: PrismaService,
private readonly mongoose: MongooseHealthIndicator,
private readonly redis: RedisHealthIndicator,
private readonly disk: DiskHealthIndicator,
private readonly memory: MemoryHealthIndicator,
private readonly indicator: HealthIndicatorService,
) {}
// Liveness: process còn chạy bình thường không, KHÔNG kiểm tra database
private readonly liveChecks: HealthIndicatorFunction[] = [
() => this.memory.checkHeap('memory_heap', 512 * 1024 * 1024),
];
// Readiness: sẵn sàng nhận request chưa (database, cache, ổ đĩa)
private readonly readyChecks: HealthIndicatorFunction[] = [
() =>
this.prismaHealth
.pingCheck('database', this.prisma)
.withTimeout(1000),
() => this.mongoose.pingCheck('mongodb').withTimeout(1000),
() => this.redis.isHealthy('redis'),
() => this.checkDisk('storage'),
];
Trong đó:
pingCheck('database', this.prisma)chạySELECT 1quaPrismaService,MongooseHealthIndicatortự lấy kết nối củaMongooseModule..withTimeout(1000): mới ở Terminus 12 (option{ timeout }cũ đã deprecated), database không trả lời trong 1 giây thì check làdown. Thửdocker pausePostgreSQL:/health/readytrả503sau khoảng 1 giây.checkHeap()so heap V8 đang dùng với ngưỡng (byte): vượt 512 MB thường do rò rỉ bộ nhớ, nên khởi động lại.
3. Custom health indicator với HealthIndicatorService.
Terminus không có indicator Redis riêng (MicroserviceHealthIndicator với Transport.REDIS chỉ thử mở kết nối mới mỗi lần và không báo degraded được), nên mình tự viết. Bản 12 đã xoá class HealthIndicator cũ, indicator tự viết dùng HealthIndicatorService: check(key) trả về một session có up(), down() và hai method mới ở bản 12: degraded() và attempt(fn) (fn chạy xong là up kèm responseTime, ném lỗi hay quá withTimeout() là down kèm message).
Redis của TaskFlow chỉ làm cache, Redis lỗi thì request vẫn chạy (Bài 29), nên mình báo degraded: status chung là degraded, HTTP vẫn 200.
- src/health/redis.health.ts
import { Inject, Injectable, type OnModuleDestroy } from '@nestjs/common';
import type { ConfigType } from '@nestjs/config';
import { HealthIndicatorService } from '@nestjs/terminus';
import { Redis } from 'ioredis';
import databaseConfig from '../config/database.config.js';
@Injectable()
export class RedisHealthIndicator implements OnModuleDestroy {
private readonly redis: Redis;
constructor(
private readonly healthIndicatorService: HealthIndicatorService,
@Inject(databaseConfig.KEY)
database: ConfigType<typeof databaseConfig>,
) {
// Mất kết nối thì lệnh lỗi ngay, không xếp hàng chờ Redis quay lại
this.redis = new Redis(database.redisUrl, {
enableOfflineQueue: false,
});
// Bắt buộc có listener 'error'; trạng thái Redis đã báo qua /health
this.redis.on('error', () => {});
}
async isHealthy<const Key extends string>(key: Key) {
const indicator = this.healthIndicatorService.check(key);
const result = await indicator
.attempt(async () => {
await this.redis.ping();
})
.withTimeout(500);
if (result[key].status === 'up') {
return result;
}
// Redis chỉ làm cache: lỗi thì API chậm hơn nhưng vẫn chạy được
return indicator.degraded({ message: String(result[key].message) });
}
async onModuleDestroy(): Promise<void> {
await this.redis.quit().catch(() => this.redis.disconnect());
}
}
Dừng container Redis rồi gọi thử:
curl -s -w " %{http_code}\n" http://localhost:3000/health/ready
# {"data":{"status":"degraded","checks":{"database":"up","mongodb":"up","redis":"degraded","storage":"up"}}} 200
Ổ đĩa cũng vậy: đầy thì upload lỗi nhưng API khác vẫn chạy. Báo down thì readiness trả 503, docker compose up --wait báo deploy lỗi, Kubernetes rút mọi pod trên node đầy khỏi Service. Nên checkDisk() đổi down thành degraded (controller inject thêm HealthIndicatorService):
- src/health/health.controller.ts (đoạn trích)
// Ổ đĩa dùng quá 90%: chỉ degraded, vì API vẫn chạy được (chỉ upload có thể lỗi).
// process.cwd() trong container là filesystem của container, không phải volume
// storage; muốn đo volume thì dùng path: join(process.cwd(), 'storage')
private async checkDisk<const Key extends string>(key: Key) {
const result = await this.disk.checkStorage(key, {
path: process.cwd(),
thresholdPercent: 0.9,
});
if (result[key].status === 'up') {
return result;
}
return this.indicator
.check(key)
.degraded({ message: String(result[key].message) });
}
Lưu ý: Dockerfile ở bài sau tạo sẵn thư mục storage (volume chứa file upload), muốn đo volume thì đổi path như comment.
4. Endpoint /health an toàn cho Docker và load balancer.
Health check được gọi từ bên ngoài nên cần:
- Đặt ngoài
/api/v1: thêm'health/*splat'vàoexcludecủasetGlobalPrefix()(src/app.setup.ts) và dùngVERSION_NEUTRAL(Bài 5). /health/live,/health/readylà@Public()(Bài 12) vì Docker, load balancer không có token.- Không lộ thông tin bên trong: PostgreSQL tắt thì message là
Can't reach database server at 127.0.0.1:5432(lộ host, cổng). Route public chỉ trả trạng thái, kết quả đầy đủ ở/health/detailscho admin (Bài 21). - Không ghi log request cho
/health/...: trongpinoHttp(Bài 26) đổi thànhautoLogging: process.env.NODE_ENV !== 'test' && { ignore: (req) => req.url?.startsWith('/health/') ?? false }. Check lỗi vẫn được Terminus ghi log.
- src/health/health.controller.ts (phần còn lại)
@Public()
@Get('live')
@HealthCheck()
async live(@Res({ passthrough: true }) res: Response) {
return summary(await this.run(res, this.liveChecks));
}
@Public()
@Get('ready')
@HealthCheck()
async ready(@Res({ passthrough: true }) res: Response) {
return summary(await this.run(res, this.readyChecks));
}
// Kết quả đầy đủ (message lỗi, responseTime...) chỉ cho admin
@Roles(['admin'])
@Get('details')
@HealthCheck()
details(@Res({ passthrough: true }) res: Response) {
return this.run(res, [...this.liveChecks, ...this.readyChecks]);
}
// Check lỗi: Terminus ném 503 kèm kết quả, mình giữ 503 và trả kết quả đó
private async run(
res: Response,
checks: HealthIndicatorFunction[],
): Promise<HealthCheckResult> {
try {
return await this.health.check(checks);
} catch (error) {
if (!(error instanceof ServiceUnavailableException)) {
throw error;
}
res.status(503);
return error.getResponse() as HealthCheckResult;
}
}
}
// Chỉ giữ trạng thái từng phần: không lộ message lỗi, host, cổng ra ngoài
function summary({ status, details }: HealthCheckResult) {
const checks = Object.fromEntries(
Object.entries(details).map(([key, value]) => [key, value.status]),
);
return { status, checks };
}
@HealthCheck() thêm header Cache-Control: no-cache và tài liệu Swagger. Cần run() vì AllExceptionsFilter (Bài 10) đổi lỗi 503 của Terminus thành thông báo chung, admin không biết check nào lỗi.
VD: Tắt PostgreSQL rồi gọi hai route public:
curl -s -w " %{http_code}\n" http://localhost:3000/health/ready
# {"data":{"status":"error","checks":{"mongodb":"up","redis":"up","storage":"up","database":"down"}}} 503
curl -s -w " %{http_code}\n" http://localhost:3000/health/live
# {"data":{"status":"ok","checks":{"memory_heap":"up"}}} 200
Load balancer ngừng gửi request, container không bị khởi động lại. Lúc này /health/details trả 500 (guard JWT cần database), chi tiết xem trong log. Trên Kubernetes, livenessProbe trỏ vào /health/live, readinessProbe vào /health/ready.
5. Lời kết.
Như vậy mình đã giới thiệu xong health check với Terminus trong NestJS: liveness và readiness, indicator có sẵn và tự viết, .withTimeout(), degraded, /health không lộ thông tin bên trong. Bài sau mình sẽ giới thiệu về deploy NestJS với Docker.
Đăng ký nhận tin.
Chúng tôi chỉ gửi tối đa 2 lần trên 1 tháng. Tuyên bố không spam mail!





0 Comments