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 nativeclusterandprocessmodules 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 totopwith 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:- Start your cluster with
pm2 start app.js -i 4(the-i 4flag spawns exactly 4 workers). - Run
pm2 monitto open a real-time dashboard showing each worker's CPU, memory usage, and live log snippets. - Use
pm2 metricsto export data for integration with tools like Prometheus or Grafana if needed.
- Start your cluster with
- AWS CloudWatch
A natural fit for AWS EC2 environments:- 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).
- 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 theprom-clientnpm 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 likepidusage(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/htopor a simpleprocessmodule 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
相关产品推荐
相关产品推荐

