Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Monitor Node.js Apps with PM2: A Practical Guide

· 6 min read · Home Tech

In this article
  1. What PM2 Monitoring Actually Covers
  2. Setting Up PM2 for Monitoring
  3. Key Metrics to Watch
  4. Using Logs for Deeper Insight
  5. Common Monitoring Pitfalls
  6. PM2 vs. Docker and Kubernetes Monitoring
  7. Cost and Resource Overhead
  8. Safety and Security Considerations
  9. Frequently Asked Questions

Yes, PM2 is a production-grade process manager for Node.js applications that provides monitoring features like real-time logs, resource usage metrics, and process health checks. This guide explains how to set up PM2 monitoring, what metrics to watch, and how to interpret them to keep your apps running reliably.

What PM2 Monitoring Actually Covers

PM2’s monitoring capabilities are built around process management. When you run an app under PM2, it tracks each process’s CPU usage, memory footprint, restart count, uptime, and event-loop delay. It also aggregates logs from stdout and stderr, and can expose metrics via a built-in HTTP endpoint or through integrations with external tools like Prometheus.

PM2 does not replace full APM (Application Performance Monitoring) tools such as New Relic or Datadog. It won’t trace individual requests, measure database query times, or profile your code. Instead, it gives you a solid operational view: is the process alive, how many resources is it using, and is it crashing or restarting unexpectedly?

Setting Up PM2 for Monitoring

First, install PM2 globally and start your app with it:

  • npm install -g pm2
  • pm2 start app.js --name my-app
  • pm2 save to persist the process list across reboots
  • pm2 startup to generate a systemd (or equivalent) service that restarts PM2 on boot

Once running, the most useful commands are:

  • pm2 list – shows a table of all apps with status, CPU, memory, restarts, and uptime.
  • pm2 monit – opens an interactive terminal dashboard with real-time CPU/memory graphs and log streams.
  • pm2 logs – streams combined logs; add --lines 100 to show recent lines.
  • pm2 describe my-app – gives detailed info including PID, script path, and the last log entries.

Key Metrics to Watch

Not all metrics are equally important. Focus on these:

  • Memory usage: A steady increase over time often indicates a memory leak. PM2 has a --max-memory-restart option (e.g., --max-memory-restart 300M) that automatically restarts the process if it exceeds that threshold.
  • CPU usage: Sustained high CPU (near 100%) can mean an infinite loop or a heavy synchronous task. It’s normal for short bursts, but not for hours.
  • Restart count: Frequent restarts suggest crashes, uncaught exceptions, or OOM kills. PM2 logs the reason for each restart in the error log.
  • Event-loop delay: PM2 reports this in its metrics (available via pm2 metrics or the API). A delay above 100ms indicates your event loop is blocked, hurting responsiveness.

You can also enable pm2 metrics to see a web-based dashboard (requires an account with PM2’s service, which is free for basic use). For self-hosted, use the pm2-server-monit module or export metrics to Prometheus via pm2-prometheus-exporter.

Using Logs for Deeper Insight

Logs are the first place to look when something goes wrong. PM2 writes to ~/.pm2/logs/ by default, with separate files for out and error. You can customize paths in the ecosystem file:

module.exports = {
  apps: [{
    name: 'my-app',
    script: 'app.js',
    out_file: '/var/log/my-app/out.log',
    error_file: '/var/log/my-app/err.log',
    merge_logs: true,
    time: true
  }]
};

The time: true option adds timestamps to each log line, which is essential for correlating with other events. Use pm2 logs --timestamp to see timestamps in real-time output.

For structured logging, integrate a library like Winston or Pino, and send logs to a central service (e.g., ELK stack) if you have multiple instances.

Common Monitoring Pitfalls

One common misconception is that PM2’s memory metric is the RSS (resident set size). That’s true, but RSS includes shared libraries and can be misleading. For a more accurate heap usage, you need to inspect the process with node --inspect or use a memory profiler. PM2’s restart threshold works on RSS, so set it based on your app’s typical baseline plus headroom.

Another pitfall is monitoring only the default metrics. PM2 doesn’t show disk I/O or network traffic. If your app is I/O-bound, you’ll need OS-level tools like iotop or nload in addition to PM2.

Also, beware of zombie processes after a crash. PM2 should clean them up, but if you see a process still listening on a port after a restart, check the error log for EADDRINUSE – it might mean the old process didn’t exit cleanly.

PM2 vs. Docker and Kubernetes Monitoring

If you run Node.js in Docker, PM2 inside the container still works, but you lose some of its benefits. Docker’s docker stats gives container-level CPU/memory, and orchestration platforms like Kubernetes have their own health checks and metrics. PM2’s restart logic is redundant if your orchestrator handles restarts. However, PM2 is still useful for development or for single-node deployments where you want a simple, battle-tested process manager without the overhead of a full platform.

For production on a single VPS, PM2 is often sufficient. For multi-container environments, rely on the platform’s monitoring and use PM2 only if you need its log management or cluster mode.

Cost and Resource Overhead

PM2 itself is open-source (MIT license) and free. The optional PM2 Plus service has a free tier and paid tiers starting at a monthly fee; it provides a hosted dashboard and alerting. Running PM2 adds minimal overhead – typically less than 10 MB of memory and negligible CPU. The main cost is your time to learn and configure it, plus the risk of misconfiguring restart thresholds.

Safety and Security Considerations

PM2 runs with the privileges of the user who started it. If you run it as root, your app also runs as root – avoid that. Create a dedicated user for your Node.js apps. Also, PM2’s web interface (if enabled) should be bound to localhost or protected with authentication, as it exposes sensitive metrics and can trigger restarts.

For the --max-memory-restart option, set it to a value that gives your app enough headroom to avoid frequent restarts under normal load, but low enough to catch leaks. A good starting point is 1.5x your app’s average memory usage.

Frequently Asked Questions

How do I see real-time CPU and memory usage in PM2?

Run pm2 monit to open an interactive dashboard. It shows per-process CPU and memory as bars, plus the last few log lines. Press ctrl+c to exit.

Why does my app restart repeatedly under PM2?

Check the error log (pm2 logs my-app --err) for uncaught exceptions or OOM messages. Also run pm2 describe my-app to see the restart reason. Common causes include unhandled promise rejections, memory limits, or a crash in a dependency.

Can PM2 send alerts when a process goes down?

Yes, but only with PM2 Plus (the hosted service) or by using a third-party tool like Slack webhooks via a custom script. The free, self-hosted PM2 does not have built-in alerting.

Does PM2 work with TypeScript or compiled apps?

Yes. You can run a compiled JavaScript file as usual. For TypeScript, use ts-node or compile to JS first. PM2 doesn’t care about the source language, only the executable script.

How do I monitor multiple Node.js apps with PM2?

Start each app with pm2 start and give them distinct names. pm2 list shows all of them. You can also group them in a single ecosystem file and use pm2 start ecosystem.config.js.

Is PM2 suitable for a high-traffic production app?

Yes, many production apps use PM2. It supports cluster mode (pm2 start app.js -i max) to run multiple instances. However, for very large-scale deployments, you might prefer a container orchestrator like Kubernetes, which offers more advanced scaling and self-healing.