温馨提示×

如何监控 Ubuntu 上的 Nodejs 应用

小樊
42
2025-11-22 12:15:33
栏目: 编程语言

监控 Ubuntu 上的 Node.js 应用

一 监控分层与总体方案

  • 进程与可用性:使用 PM2systemd 保证进程常驻、自动重启,并快速查看状态与日志。
  • 系统资源:用 htopNetData 观察 CPU、内存、I/O、网络 等系统层面指标与瓶颈。
  • 应用指标与可视化:在 Node.js 中暴露 Prometheus 指标,配合 Grafana 做仪表盘与告警。
  • 日志:结构化日志(如 Winston),结合 journalctl 与集中式方案(如 ELK)做检索与告警。
  • 链路与错误:接入 APM(如 New Relic、Datadog)获取 HTTP 延迟、错误率、调用链 等。
  • 可用性探测:用 Uptime KumaHTTP/端口/心跳 探测与通知。

二 快速上手 PM2 与 systemd

  • PM2 常用命令
    • 安装与启动:sudo npm install pm2 -gpm2 start app.js --name “my-app”
    • 状态与资源:pm2 statuspm2 monit
    • 日志:pm2 logs my-app(实时查看与轮转)
  • systemd 服务示例
    • 创建服务:sudo nano /etc/systemd/system/my-app.service
    • 内容要点:
      [Unit]
      Description=Node.js Application
      After=network.target
      
      [Service]
      Type=simple
      User=<your-user>
      WorkingDirectory=/path/to/your/app
      ExecStart=/usr/bin/node /path/to/your/app/app.js
      Restart=always
      
      [Install]
      WantedBy=multi-user.target
      
    • 启用与查看:sudo systemctl daemon-reloadsudo systemctl start my-appsudo systemctl status my-app
  • 适用场景
    • PM2 适合快速部署与运行时观测(开发/生产均可)。
    • systemd 适合系统级托管、开机自启与与系统日志联动。

三 日志监控与最佳实践

  • 应用内结构化日志
    • 使用 Winston 输出到控制台与文件,便于检索与聚合:
      const winston = require('winston');
      const logger = winston.createLogger({
        level: 'info',
        format: winston.format.json(),
        transports: [
          new winston.transports.File({ filename: 'error.log', level: 'error' }),
          new winston.transports.File({ filename: 'combined.log' })
        ]
      });
      logger.info('Application started');
      logger.error('An error occurred:', error);
      
  • 系统与服务日志
    • 查看服务日志:journalctl -u my-app.service -f(实时跟踪)
    • 快速跟踪文件:tail -f combined.log
  • 集中式与可视化
    • 小规模可用 PM2 自带日志;中大规模建议接入 ELK(Elasticsearch/Logstash/Kibana) 或云日志服务做统一检索、分析与告警。

四 指标与可视化 告警

  • Prometheus + Grafana
    • 在应用中引入 prom-client 暴露指标,并新增 /metrics 端点;示例(记录 HTTP 请求时延):
      const client = require('prom-client');
      const httpRequestDuration = new client.Histogram({
        name: 'http_request_duration_ms',
        help: 'Duration of HTTP requests in ms',
        labelNames: ['method', 'route', 'code'],
        buckets: [0.1, 5, 15, 50, 100, 200, 300, 400, 500]
      });
      
      app.use((req, res, next) => {
        const start = Date.now();
        res.on('finish', () => {
          httpRequestDuration
            .labels(req.method, req.route || req.path, res.statusCode)
            .observe(Date.now() - start);
        });
        next();
      });
      
    • 配置 Prometheus 抓取 /metrics,在 Grafana 中构建仪表盘并设置阈值告警。
  • 系统与应用性能面板
    • NetData:一键安装并访问 http://:19999 查看实时系统与应用指标。
    • Uptime Kuma:自托管可用性监控,访问 http://:3001,支持 HTTP/端口/心跳 探测与 Telegram/Discord/Slack 通知。

五 进阶排障与性能分析

  • 内存与 CPU 快照
    • 使用 heapdump 生成堆快照定位内存泄漏:
      const heapdump = require('heapdump');
      heapdump.writeSnapshot('/path/to/snapshot.heapsnapshot');
      
    • Chrome DevTools Memory 面板分析快照。
  • 运行时诊断
    • 使用 node --inspect 配合 Chrome DevToolsCPU/内存 性能分析。
  • 系统层面观测
    • 结合 top/htop、vmstat、iostat、free、df 等工具排查 CPU 饱和、内存不足、I/O 瓶颈、磁盘空间 等问题。

0