许多时候,我们需要对应用进行监控,来获取他的详细状态,这节介绍几个在 express 中进行健康检查的方案。
亲自创建一些路由,根据情况返回应用的相关信息,不过自己写比较麻烦,除非有特别的需求,一般我们就用第三方的解决方案。
express-actuator.js 是一个现成的用于 express 的健康检查中间件:
npm install express-acutator --save
配置express-actuator:
在你的主应用中引入 actuator 即可:
const actuator = require('express-actuator');
const app = express();
app.use(actuator({
basePath: '/actuator',
infoGitMode: 'simple',
// infoBuildOptions: null, // extra information you want to expose in the build object. Requires an object.
// infoDateFormat: null, // by default, git.commit.time will show as is defined in git.properties. If infoDateFormat is defined, moment will format git.commit.time. See https://momentjs.com/docs/#/displaying/format/.
customEndpoints: [] // array of custom endpoints
}));
其中有一些配置选项:
访问端点:
{
"build": {
"description": "This is my new app",
"name": "MyApp",
"version": "1.0.0"
},
"git": {
"branch": "master",
"commit": {
"id": "329a314",
"time": "2016-11-18 08:16:39-0500"
}
}
}
{
"mem": {
"rss": 39350272,
"heapTotal": 11038720,
"heapUsed": 8889952,
"external": 892742,
"arrayBuffers": 32982
},
"uptime": 58.3234052
}
{
"status": "UP"
}
lightship.js 也是一个不错的健康检查工具,并且可以与 Kubernetes 集成:
npm install lightship --save
不过与 express-actuator 不同的是,express-actuator是挂载在 express 应用上的中间件,而 lightship 是自己单独开辟一个 http 服务器(即额外占用一个端口):
async function start() {
const config = require('./config').get();
const init = require('./init');
await init();
const express = require('express');
const jsTextChart = require('js-text-chart');
const logger = require('./utils/logger');
const server = require('./utils/server');
const Lightship = await import('lightship');
const createLightship = Lightship.createLightship;
const app = require('./app');
const lightship = await createLightship({
detectKubernetes: false,
port: 8081,
// gracefulShutdownTimeout, // 优雅停机时间
// gracefulShutdownTimeout, // 优雅停机延迟
// shutdownHandlerTimeout, // 停机Handler时间
// signals, // An a array of [signal events]{@link https://nodejs.org/api/process.html#process_signal_events}. Default: [SIGTERM].
// terminate // Default: `() => { process.exit(1) };`
});
server.on('request', app);
server.listen(config.app.port, config.app.host, async() => {
let host = server.address().address;
let port = server.address().port;
let str = config.app.name;
let mode = [ "close", "far", undefined ];
let chart = jsTextChart.convert(str, mode[0]);
console.log(chart);
console.log("Server is ready on http://%s:%s", host, port);
lightship.registerShutdownHandler(() => {
lightship.shutdown();
server.close();
})
lightship.signalReady();
});
}
start();
其中有一些配置选项:
访问端点:
Kubernates 提供了两个健康检查服务:liveness 和 readiness,你可以将 express 部署到 Kubernates 容器中。