Deployment & Process Managers (PM2)

5 questions found

What problem does PM2 solve for running a Node.js application in production, beyond just executing 'node server.js'?

Beginner
Running 'node server.js' directly leaves the process with no automatic restart if it crashes, no built-in way to run multiple instances across CPU cores, no persistent log management, and it stops entirely if the terminal session ends -- PM2 is a production process manager that handles automatic restarts on crash, clustering across cores, log file management and rotation, and keeps the application running detached from any specific terminal session, persisting across SSH disconnects and (with setup) system reboots.
npm install -g pm2

pm2 start server.js --name my-app
pm2 list          # view running processes
pm2 logs my-app    # tail logs
pm2 restart my-app
pm2 stop my-app
Real-world example A team that previously ran their Node.js API with 'node server.js' inside a tmux session (which occasionally crashed silently overnight, going unnoticed until customers complained) switches to PM2, which automatically restarts the process within seconds of any crash and keeps a searchable log history of exactly what happened each time.

Common follow-ups: How does PM2 differ from using a systemd service to achieve similar restart-on-crash behavior?;What's the risk of relying solely on PM2's auto-restart without also investigating why the process crashed in the first place?

Clustering & Worker Threads;Logging & Monitoring

How do you configure PM2 using an ecosystem.config.js file rather than passing options directly on the command line?

Intermediate
An ecosystem file defines one or more applications' configuration (script path, instance count, environment variables per environment, restart behavior, memory limits) in a single version-controlled JavaScript or JSON file, making deployment configuration reproducible, reviewable via source control, and consistent across environments rather than relying on manually remembered command-line flags.
// ecosystem.config.js
module.exports = {
  apps: [{
    name: 'my-app',
    script: './server.js',
    instances: 'max',
    exec_mode: 'cluster',
    env_production: { NODE_ENV: 'production', PORT: 3000 },
    max_memory_restart: '500M',
  }],
};

// pm2 start ecosystem.config.js --env production
Real-world example A team checks their ecosystem.config.js into version control alongside their application code, ensuring the exact same process configuration (instance count, memory limits, environment variables) is used identically whenever any team member or CI pipeline deploys the application, rather than relying on someone remembering the correct command-line flags.

Common follow-ups: How do you manage different environment variable sets (staging vs production) within a single ecosystem file?;What does max_memory_restart actually do, and when is automatically restarting on high memory usage the wrong response to a real leak?

Environment Variables & Configuration;CI/CD Publishing & Deployment

How does PM2's built-in log management work, and how would you configure log rotation to prevent log files from growing unbounded?

Advanced
PM2 automatically captures each managed process's stdout and stderr into log files under ~/.pm2/logs by default, but without rotation these files grow indefinitely and can eventually exhaust disk space -- the pm2-logrotate module (installed as a PM2 module, not an npm package) automatically rotates logs based on size or a schedule, compresses old logs, and prunes logs beyond a configured retention period.
pm2 install pm2-logrotate

pm2 set pm2-logrotate:max_size 50M
pm2 set pm2-logrotate:retain 14
pm2 set pm2-logrotate:compress true
Real-world example A production server that ran out of disk space after months of continuous operation, traced to an unbounded PM2 log file that had grown to over 40GB, is fixed by installing pm2-logrotate configured to rotate logs at 50MB and retain only the last 14 rotated files, compressed.

Common follow-ups: How does PM2's log handling compare to sending logs to a centralized logging service like Datadog or an ELK stack instead?;What's the risk of losing recent log data if a log rotation happens at exactly the wrong moment during an active incident?

Logging & Monitoring;Docker & Containerization for Node.js

How do you configure PM2 to automatically restart your Node.js application after a server reboot?

Intermediate
PM2's 'startup' command generates and configures a system-specific init script (systemd on most modern Linux distributions) that starts PM2 itself automatically on system boot; combined with 'pm2 save' (which persists the current list of running processes to a dump file), PM2 will automatically restore and restart every previously running application after the server reboots, without any process being lost.
pm2 startup           # generates and prints a system-specific command to run
# (run the printed command, e.g. with sudo, to actually register the startup script)

pm2 save              # saves the currently running process list
# After a reboot, PM2 automatically restores everything from this saved list
Real-world example A production server that was manually restarted for a security patch came back up with the Node.js API not running at all until an engineer noticed and manually started it again; running 'pm2 startup' and 'pm2 save' beforehand ensures the application resumes automatically on any future reboot without manual intervention.

Common follow-ups: What happens if 'pm2 save' isn't run after adding a new application, and the server later reboots?;How does this systemd-based startup mechanism differ from relying on a Docker container's own restart policy in a containerized deployment?

Cloud & DevOps;Docker & Containerization for Node.js

What does PM2's built-in monitoring dashboard (pm2 monit, or PM2 Plus) show, and what metrics are most useful for production operations?

Advanced
'pm2 monit' provides a real-time terminal dashboard showing each managed process's CPU usage, memory usage, and a live tail of recent log output; PM2 Plus (a paid hosted service) extends this with a web-based dashboard, historical metrics, custom application-level metrics, exception tracking, and alerting -- for production operations, the most actionable metrics are typically memory trend (to catch leaks before they cause a crash), restart count (frequent unexpected restarts signal an underlying problem), and CPU usage relative to the number of cluster instances running.
pm2 monit  # real-time terminal dashboard

# Programmatic access to the same metrics
pm2 jlist  # JSON output of all process metrics, useful for scripting alerts
Real-world example An operations team notices via 'pm2 monit' that one specific cluster worker's memory usage climbs steadily every few hours while its siblings remain stable, pointing them toward a memory leak that's somehow specific to whichever requests happen to land on that particular worker rather than an application-wide issue.

Common follow-ups: How would you pipe PM2's metrics into an external monitoring system like Prometheus or Datadog for longer-term historical analysis and alerting?;What does a consistently high restart count for a specific process typically indicate that CPU or memory metrics alone might not reveal?

Logging & Monitoring;Performance Optimization & Profiling