温馨提示×

debian nodejs如何监控

小樊
46
2026-10-19 22:10:55
栏目: 编程语言

在 Debian 上监控 Node.js 应用,可以从系统层、进程层、应用层、日志层几个维度来做。下面按实用程度给你一套方案。


一、系统 / 进程级监控(最基础)

1. 使用 systemd(推荐)

如果你用 systemd 管理 Node.js 服务:

systemctl status yourapp
journalctl -u yourapp -f

优点

  • 自动重启
  • 标准日志
  • 资源占用可查

配置示例 /etc/systemd/system/yourapp.service:

[Unit]
Description=Node.js App

[Service]
ExecStart=/usr/bin/node /var/www/app/index.js
Restart=always
User=node
Environment=NODE_ENV=production

[Install]
WantedBy=multi-user.target

2. 基础命令

top
htop
ps aux | grep node

查看内存 / CPU:

pidstat -p <pid> 1

二、Node.js 内置监控(应用层)

1. Node.js 内置指标

console.log(process.memoryUsage());
console.log(process.cpuUsage());

2. 健康检查接口(强烈推荐)

app.get('/health', (req, res) => {
  res.json({
    uptime: process.uptime(),
    memory: process.memoryUsage(),
    cpu: process.cpuUsage()
  });
});

可用 curl 或 Prometheus 抓取。


三、专业监控方案(生产推荐)

方案 A:Prometheus + Node Exporter + Grafana(最主流)

1. 安装 Node Exporter

apt install prometheus-node-exporter

2. Node.js 暴露指标

npm install prom-client
const client = require('prom-client');
const collectDefaultMetrics = client.collectDefaultMetrics;
collectDefaultMetrics();

app.get('/metrics', async (req, res) => {
  res.set('Content-Type', client.register.contentType);
  res.end(await client.register.metrics());
});

3. Prometheus 抓取

scrape_configs:
  - job_name: nodejs
    static_configs:
      - targets: ['localhost:3000']

4. Grafana 看板

  • 导入 Dashboard ID:1860(Node Exporter)
  • Node.js 自定义 Dashboard

方案 B:PM2(最简单)

npm install -g pm2
pm2 start app.js
pm2 monit
pm2 logs

监控指标:

  • CPU
  • 内存
  • 重启次数

Web 面板(可选):

pm2 plus

方案 C:商业 / SaaS

  • Datadog
  • New Relic
  • Elastic APM

适合大团队、复杂系统。


四、日志监控(很重要)

1. 日志聚合

apt install rsyslog

或用:

  • Loki + Grafana
  • ELK

2. 异常捕获

process.on('uncaughtException', e => {
  console.error('uncaught', e);
});
process.on('unhandledRejection', e => {
  console.error('unhandled', e);
});

五、推荐组合(实战)

小型项目

systemd + PM2 + 健康检查接口

中型 / 生产

systemd + Prometheus + Grafana + Loki

大型

APM(Datadog / New Relic)+ 全链路监控


如果你愿意,可以告诉我:

  • Node.js 版本
  • 是否 Docker
  • 单服务还是集群
  • 是否需要报警

我可以直接帮你写 完整监控配置。

0 踩