如何暴露 /health 端点来检查数据库连接是否正常?
解读
国内生产环境普遍要求服务在 Kubernetes / 云原生平台中存活探针(liveness)与就绪探针(readiness)都能通过,否则 Pod 会被反复重启或从负载均衡中摘除。/health 是最常见的探针路径,它必须:
- 快速返回(<200 ms),避免阻塞调度;
- 只依赖“关键依赖”——对 90% 业务系统而言就是数据库;
- 返回明确的状态码:200 表示健康,5xx 表示异常;
- 不能抛出未捕获异常,否则直接被判“宕机”。
MikroORM 的“数据映射器”架构把 EntityManager 包装在请求上下文(RequestContext)里,但 /health 通常运行在全局作用域,因此需要手动拿到全局的 MikroORM 实例并执行一条最轻量的 SQL(如 SELECT 1)。同时,国内面试官会追问“你怎么保证连接池没耗尽”“你怎么防止慢查询拖垮探针”,所以答案里必须体现超时、重试、连接池状态检查等细节。
知识点
- MikroORM 初始化后,全局 ORM 实例提供 isConnected() 与 getConnection() 方法;
- Connection 的 execute() 可运行原生 SQL,并支持 timeout 选项(mikro-orm@5.4+);
- 连接池健康度:通过 Connection.getPoolStatus()?.waitingCount 判断是否排队过多;
- 探针超时:Node 端使用 Promise.race + AbortController 或 setTimeout 做 3 秒兜底;
- 框架集成:NestJS 用 @Get('health')、Express 用 router.get('/health', handler);
- 返回体规范:国内大厂普遍采用阿里 SLS、腾讯云监控格式,建议 { status: 'ok', db: 'up', latency: 12 };
- 灰度发布:/health 不能走业务路由中间件(如鉴权、限流),需白名单放行。
答案
以下给出可直接落地的 NestJS 示例,Express 同理可迁移。核心思路:全局 ORM → 轻量探测 → 超时保护 → 明确状态码。
// health.controller.ts
import { Controller, Get, HttpCode, HttpStatus, ServiceUnavailableException } from '@nestjs/common';
import { MikroORM } from '@mikro-orm/core';
@Controller('health')
export class HealthController {
constructor(private readonly orm: MikroORM) {}
@Get()
@HttpCode(HttpStatus.OK)
async health() {
const start = Date.now();
try {
// 1. 连接池排队过多直接判失败
const pool = this.orm.em.getConnection().getPoolStatus();
if (pool && pool.waitingCount > 5) {
throw new Error('db pool exhausted');
}
// 2. 执行一条最轻量的 SQL,3 秒超时
const timeout = 3000;
const sql = this.orm.em.getConnection().execute('SELECT 1 as ok', [], 'get', timeout);
// 3. Promise.race 兜底
const ok = await Promise.race([
sql,
new Promise<never>((_, reject) =>
setTimeout(() => reject(new Error('db probe timeout')), timeout),
),
]);
// 4. 返回统一格式
return {
status: 'ok',
db: 'up',
latency: Date.now() - start,
};
} catch (e) {
// 5. 任何异常都返回 503,K8s 会摘除 Pod
throw new ServiceUnavailableException({
status: 'error',
db: 'down',
message: e.message,
});
}
}
}
注册控制器后,访问 GET /health:
- 数据库正常 → 200 { status: 'ok', db: 'up', latency: 8 }
- 连接失败或超时 → 503 { status: 'error', db: 'down', message: 'db probe timeout' }
拓展思考
- 多数据源:如果项目同时连接 PostgreSQL 与 MongoDB,可在 /health 里并行探测,只要一个失败就返回 503,避免“半死不活”状态;
- 只读库与主库:国内电商大促期间会把只读库弹性扩容,探针需区分读写角色,防止主库挂掉但只读库正常时误判“服务健康”;
- 缓存探针:Redis 也是关键依赖,可再增加 redis.ping(),但注意 Redis 集群版要遍历所有 master 节点;
- 冷启动优化:MikroORM 在首次连接时可能拉取元数据,导致 /health 超时,建议在 AppModule 的 onModuleInit 里提前 await orm.connect(),把连接池预热完成后再监听端口;
- 指标上报:把 latency、pool.waitingCount 写入 Prometheus Gauge,配合阿里云 ARMS 或腾讯云 TSF 做告警,比单纯探针更提前发现抖动;
- 安全加固:/health 路径虽然无需鉴权,但要防止外网直接扫描,可在 Ingress 层只对内网段开放,或返回体中去掉堆栈信息,避免泄露 ORM 版本。