You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js集群模式:如何监控每个Worker进程的CPU与内存

Great question! Since you're running a Node.js cluster on an AWS EC2 instance with 4 cores and 7.5GB RAM, keeping an eye on individual worker processes' CPU and memory usage is crucial for spotting bottlenecks and ensuring your app runs smoothly. Let's break down your options, from quick-and-easy built-in tools to robust production-grade solutions:

Built-in Tools & System Utilities (No Extra Dependencies)

These are perfect for quick debugging or ad-hoc checks without adding extra packages:

  • Node.js Cluster + Process Modules
    You can leverage Node.js's native cluster and process modules to have each worker report its resource usage to the master process. Set up a timer in each worker to collect metrics, then send them to the master via inter-process communication.
    Example code snippet:
    // In worker processes
    const os = require('os');
    setInterval(() => {
      const memUsage = process.memoryUsage();
      const cpuUsage = process.cpuUsage();
      // Calculate CPU percentage adjusted for core count
      const cpuPercent = (cpuUsage.user + cpuUsage.system) / 1000 / os.cpus().length;
      
      process.send({
        type: 'metrics',
        pid: process.pid,
        memory: `${Math.round(memUsage.rss / 1024 / 1024)} MB`,
        cpu: `${cpuPercent.toFixed(2)}%`
      });
    }, 1000);
    
    // In master process
    cluster.on('message', (worker, msg) => {
      if (msg.type === 'metrics') {
        console.log(`Worker ${msg.pid} | Memory: ${msg.memory} | CPU: ${msg.cpu}`);
      }
    });
    
  • System Command-Line Tools
    Use these directly in your EC2 terminal:
    • top -p <pid1>,<pid2>,<pid3>,<pid4>: Specify your 4 worker PIDs to get real-time CPU and memory usage for each process.
    • htop: A more intuitive alternative to top with color-coded resource usage and easy Node.js process filtering.
    • ps aux | grep node: List all Node.js processes to quickly check PID, CPU percentage, and memory percentage for each worker.
Third-Party Process Monitors (Production-Friendly)

For long-term monitoring, alerting, and visualization, these tools are built for production workloads:

  • PM2
    The most popular Node.js process manager with native cluster support:
    1. Start your cluster with pm2 start app.js -i 4 (the -i 4 flag spawns exactly 4 workers).
    2. Run pm2 monit to open a real-time dashboard showing each worker's CPU, memory usage, and live log snippets.
    3. Use pm2 metrics to export data for integration with tools like Prometheus or Grafana if needed.
  • AWS CloudWatch
    A natural fit for AWS EC2 environments:
    1. Install the CloudWatch Agent on your EC2 instance and configure it to collect process-level metrics (target Node.js workers by PID or process name).
    2. View worker-specific CPU and memory data in the CloudWatch console, and set up alert rules (e.g., trigger a notification if a worker's CPU exceeds 80% for 5 minutes).
  • New Relic / Datadog
    Full-stack APM tools that automatically detect Node.js clusters:
    Install their respective npm packages, configure your account key, and you'll get out-of-the-box visibility into each worker's CPU, memory, request latency, error rates, and more. Both tools offer customizable dashboards and intelligent alerting.
Custom Monitoring Solutions (Full Control)

If you need to integrate with internal systems or fully customize monitoring logic:

  • Prometheus + prom-client
    Use the prom-client npm package to expose metrics endpoints in each worker, then configure Prometheus to scrape these endpoints. Pair it with Grafana to build custom dashboards tracking worker resource usage over time.
  • PID-Based Scripts
    Use packages like pidusage (cross-platform) in a dedicated monitoring process or master process to periodically fetch CPU and memory data for each worker PID. You can then send this data to your internal logging system or alerting service.

Quick Recap:

  • For quick checks: Use top/htop or a simple process module script.
  • For production simplicity: Go with PM2 for built-in cluster monitoring.
  • For AWS-native visibility: Use CloudWatch with process-level metrics.
  • For full customization: Build a solution with Prometheus + Grafana.

内容的提问来源于stack exchange,提问作者RC_02

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:55:10