Bird
Raised Fist0
Node.jsframework~15 mins

PM2 for process management in Node.js - Deep Dive

Choose your learning style10 modes available
Overview - PM2 for process management
What is it?
PM2 is a tool that helps you run and manage Node.js applications easily. It keeps your apps running all the time, restarts them if they crash, and helps you control multiple apps at once. You can also use it to see how your apps are doing and manage their logs. It works like a manager that watches over your Node.js programs to keep them healthy and organized.
Why it matters
Without PM2, if your Node.js app crashes or stops, you would have to restart it manually, which can cause downtime and lost users. Managing many apps or servers becomes hard and error-prone. PM2 solves this by automatically restarting apps, balancing load, and giving you tools to monitor and control your processes. This means your apps stay online longer and you spend less time fixing crashes.
Where it fits
Before learning PM2, you should know basic Node.js and how to run scripts from the command line. After PM2, you can learn about advanced deployment tools, container orchestration like Docker and Kubernetes, or monitoring solutions like Prometheus. PM2 fits as a practical step to keep your Node.js apps running smoothly in real environments.
Mental Model
Core Idea
PM2 acts like a smart supervisor that watches your Node.js apps, restarts them if they fail, and helps you manage many apps easily from one place.
Think of it like...
Imagine you have a team of cooks in a kitchen. PM2 is like the head chef who watches all the cooks, makes sure no one stops working, replaces anyone who gets tired, and keeps the kitchen running smoothly without you needing to check every minute.
┌───────────────┐
│   PM2 Manager │
├───────────────┤
│ Watches Apps  │
│ Restarts if   │
│ Crashed       │
│ Balances Load │
│ Shows Logs    │
└──────┬────────┘
       │
┌──────▼───────┐   ┌───────────────┐
│ Node App 1   │   │ Node App 2    │
│ (Running)   │   │ (Running)     │
└─────────────┘   └───────────────┘
Build-Up - 7 Steps
1
FoundationWhat is PM2 and why use it
🤔
Concept: Introducing PM2 as a process manager for Node.js apps and its basic purpose.
PM2 is a tool you install on your computer or server. It helps you start your Node.js app and keeps it running. If your app crashes, PM2 restarts it automatically. This means your app stays online without you needing to watch it all the time.
Result
Your Node.js app runs continuously and restarts automatically if it crashes.
Understanding that PM2 automates app restarts saves you from manual restarts and downtime.
2
FoundationInstalling and starting apps with PM2
🤔
Concept: How to install PM2 and start a Node.js app using it.
You install PM2 globally using npm: npm install -g pm2. Then you start your app with pm2 start app.js. PM2 runs your app in the background and shows you its status with pm2 list.
Result
PM2 runs your app in the background and you can see it listed as running.
Knowing how to install and start apps with PM2 is the first step to managing Node.js processes easily.
3
IntermediateManaging multiple apps and process lists
🤔Before reading on: do you think PM2 can manage only one app at a time or multiple apps simultaneously? Commit to your answer.
Concept: PM2 can manage many apps at once and lets you see their status in one place.
You can start many apps with PM2 by running pm2 start app1.js and pm2 start app2.js. Use pm2 list to see all running apps with their IDs, status, and memory use. You can stop, restart, or delete apps by their ID or name.
Result
You control multiple Node.js apps easily from one command line interface.
Understanding that PM2 manages multiple apps helps you organize complex projects or servers with many services.
4
IntermediateAutomatic restarts and crash recovery
🤔Before reading on: do you think PM2 restarts apps only when you tell it or automatically when they crash? Commit to your answer.
Concept: PM2 watches your apps and restarts them automatically if they crash or stop unexpectedly.
If your app crashes due to an error, PM2 detects this and restarts it immediately. This keeps your app available without manual intervention. You can also configure PM2 to restart apps on file changes during development.
Result
Your app recovers from crashes automatically, reducing downtime.
Knowing PM2's automatic restart feature means you can trust your app to stay online even if bugs cause crashes.
5
IntermediateUsing PM2 logs and monitoring tools
🤔
Concept: PM2 collects logs and provides monitoring commands to check app health and performance.
PM2 saves your app's output and error messages in log files. You can view logs with pm2 logs or pm2 monit to see CPU and memory usage live. This helps you find problems and understand app behavior.
Result
You get real-time insight into your app's performance and errors.
Access to logs and monitoring helps you debug and optimize your apps effectively.
6
AdvancedConfiguring PM2 with ecosystem files
🤔Before reading on: do you think PM2 requires you to start each app manually every time or can it use a config file to manage multiple apps? Commit to your answer.
Concept: PM2 supports ecosystem configuration files to define multiple apps and settings in one place.
You create a file called ecosystem.config.js where you list your apps, their script paths, environment variables, and options like restart delays. Then you start all apps with pm2 start ecosystem.config.js. This makes managing many apps easier and repeatable.
Result
You manage complex app setups with one config file and simple commands.
Using ecosystem files scales PM2 management from simple to complex projects smoothly.
7
ExpertPM2 internals and cluster mode benefits
🤔Before reading on: do you think PM2 runs your app as a single process only or can it run multiple copies to use all CPU cores? Commit to your answer.
Concept: PM2 can run your app in cluster mode, creating multiple processes to use all CPU cores and improve performance.
In cluster mode, PM2 starts several instances of your app that share the same port. This spreads the load across CPU cores, improving speed and reliability. PM2 also balances requests between instances and restarts any that crash without affecting others.
Result
Your app runs faster and is more resilient by using all CPU cores efficiently.
Understanding cluster mode unlocks PM2's power to scale Node.js apps on a single machine.
Under the Hood
PM2 runs your Node.js app as a child process and monitors it continuously. It listens for exit events to detect crashes and automatically restarts the process. In cluster mode, PM2 uses Node.js's cluster module to fork multiple worker processes that share the same server port. PM2 also manages log files by redirecting stdout and stderr streams to files. It keeps a process list in memory and on disk to remember app states across system restarts.
Why designed this way?
PM2 was designed to solve the problem of keeping Node.js apps alive in production without manual restarts. Node.js apps run in a single thread, so crashes stop the app entirely. PM2 uses child processes and clustering to improve reliability and performance. Alternatives like forever existed but lacked cluster support and advanced monitoring. PM2 balances simplicity with powerful features to serve both beginners and professionals.
┌───────────────┐
│   PM2 Master  │
│  (Manager)    │
├──────┬────────┤
│      │        │
│      ▼        ▼
│  ┌────────┐ ┌────────┐
│  │Worker 1│ │Worker 2│
│  │Process │ │Process │
│  └────────┘ └────────┘
│      │        │
│  ┌───────────────┐
│  │App Code (Node)│
│  └───────────────┘
│
│ Logs & Monitoring
└─────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does PM2 automatically restart your app only on crashes or also on normal exits? Commit to your answer.
Common Belief:PM2 only restarts apps if they crash unexpectedly, not if they exit normally.
Tap to reveal reality
Reality:PM2 restarts apps on any exit unless configured otherwise, including normal exits.
Why it matters:If you expect PM2 to ignore normal exits, your app might restart unexpectedly, causing loops or resource issues.
Quick: Do you think PM2 replaces the need for load balancers in production? Commit to yes or no.
Common Belief:PM2 can replace load balancers by running multiple app instances on one server.
Tap to reveal reality
Reality:PM2's cluster mode balances load on one machine but does not replace external load balancers for multiple servers.
Why it matters:Relying on PM2 alone for load balancing across servers can cause performance bottlenecks and single points of failure.
Quick: Is PM2 only useful for Node.js apps? Commit to yes or no.
Common Belief:PM2 works only with Node.js applications.
Tap to reveal reality
Reality:PM2 can manage any process, including scripts in other languages, though it is optimized for Node.js.
Why it matters:Limiting PM2 use to Node.js misses its flexibility to manage other background processes.
Quick: Does PM2 automatically save your app's state and restart it after a server reboot without extra setup? Commit to yes or no.
Common Belief:PM2 automatically restarts apps after server reboot without any configuration.
Tap to reveal reality
Reality:You must configure PM2 startup scripts to enable automatic restart on reboot.
Why it matters:Without setup, your apps won't restart after reboot, causing unexpected downtime.
Expert Zone
1
PM2's cluster mode uses Node.js's internal cluster module, which shares server ports but requires your app to be stateless or handle shared state carefully.
2
PM2 supports graceful reloads that restart app instances one by one to avoid downtime, but this requires your app to handle connections properly.
3
PM2's ecosystem files support environment-specific variables and advanced options like max memory restarts, which help in fine-tuning production behavior.
When NOT to use
PM2 is not ideal for containerized environments where orchestration tools like Kubernetes manage process lifecycles. For very simple scripts or one-off tasks, PM2 adds unnecessary complexity. Alternatives like systemd or Docker may be better for system-level process management or containerized apps.
Production Patterns
In production, PM2 is often used with ecosystem files to manage multiple microservices. It integrates with log aggregation tools by forwarding logs. Teams use PM2's monitoring and alerting features to detect crashes early. Cluster mode is enabled to maximize CPU usage on servers. Startup scripts ensure apps restart after server reboots.
Connections
Systemd service manager
Both manage processes and ensure they run continuously, but systemd is OS-level while PM2 is app-level.
Understanding systemd helps grasp how PM2 fits as a user-friendly, Node.js-focused alternative for process management.
Load balancing in networking
PM2's cluster mode balances load across CPU cores like load balancers distribute network traffic across servers.
Knowing load balancing concepts clarifies how PM2 improves app performance by spreading work efficiently.
Project management and team leadership
PM2 acts like a team leader ensuring all team members (processes) work well and recover from problems.
Seeing PM2 as a leadership role helps understand its responsibility for app health and coordination.
Common Pitfalls
#1Not setting up PM2 to restart apps on server reboot.
Wrong approach:pm2 start app.js # No further setup
Correct approach:pm2 start app.js pm2 startup pm2 save
Root cause:Assuming PM2 automatically restarts apps after reboot without configuring startup scripts.
#2Running multiple app instances without cluster mode to use all CPU cores.
Wrong approach:pm2 start app.js -i 1
Correct approach:pm2 start app.js -i max
Root cause:Not knowing the -i max option enables cluster mode to fork processes equal to CPU cores.
#3Ignoring logs and monitoring, making debugging hard.
Wrong approach:pm2 start app.js # No log checks
Correct approach:pm2 start app.js pm2 logs pm2 monit
Root cause:Not using PM2's built-in tools to track app health and errors.
Key Takeaways
PM2 is a powerful process manager that keeps Node.js apps running by automatically restarting them if they crash.
It can manage multiple apps at once and provides tools to monitor performance and logs in real time.
Cluster mode allows PM2 to run multiple app instances to use all CPU cores, improving speed and reliability.
Using ecosystem config files helps manage complex app setups with ease and repeatability.
Proper setup of startup scripts is essential to ensure apps restart after server reboots, preventing downtime.

Practice

(1/5)
1. What is the primary purpose of PM2 in Node.js application management?
easy
A. To keep Node.js applications running and restart them if they crash
B. To compile Node.js code into machine code
C. To serve static files like images and CSS
D. To replace the Node.js runtime environment

Solution

  1. Step 1: Understand PM2's role

    PM2 is a process manager designed to keep Node.js apps alive and restart them automatically if they crash.
  2. Step 2: Compare options

    Options A, B, and C describe unrelated tasks like replacing the runtime, compiling code, or serving static files, which PM2 does not do.
  3. Final Answer:

    To keep Node.js applications running and restart them if they crash -> Option A
  4. Quick Check:

    PM2 = process manager for app uptime [OK]
Hint: PM2 manages app uptime and restarts crashed apps [OK]
Common Mistakes:
  • Confusing PM2 with a compiler or bundler
  • Thinking PM2 serves static content
  • Believing PM2 replaces Node.js runtime
2. Which of the following is the correct command to start an app named app.js using PM2?
easy
A. pm2 run app.js
B. pm2 launch app.js
C. pm2 start app.js
D. pm2 execute app.js

Solution

  1. Step 1: Recall PM2 start command

    The correct command to start an app with PM2 is pm2 start <file>.
  2. Step 2: Verify options

    Options A, B, and D use incorrect verbs like run, launch, or execute which are not valid PM2 commands.
  3. Final Answer:

    pm2 start app.js -> Option C
  4. Quick Check:

    Start app = pm2 start [OK]
Hint: Use 'pm2 start' to launch apps [OK]
Common Mistakes:
  • Using 'pm2 run' instead of 'pm2 start'
  • Confusing PM2 commands with other tools
  • Typing 'pm2 launch' which is invalid
3. Given the following PM2 command sequence:
pm2 start app.js --name myapp
pm2 restart myapp
pm2 stop myapp
pm2 delete myapp

What is the state of myapp after these commands?
medium
A. The app crashed and PM2 is trying to restart it
B. The app is stopped but still listed in PM2 process list
C. The app is running and managed by PM2
D. The app is removed from PM2 process list

Solution

  1. Step 1: Analyze each command effect

    pm2 start app.js --name myapp starts and names the app. pm2 restart myapp restarts it. pm2 stop myapp stops it but keeps it listed. pm2 delete myapp removes it from PM2's list.
  2. Step 2: Determine final state

    After deletion, the app is no longer managed or listed by PM2.
  3. Final Answer:

    The app is removed from PM2 process list -> Option D
  4. Quick Check:

    Delete removes app from PM2 list [OK]
Hint: Delete removes app from PM2 list, stop just pauses it [OK]
Common Mistakes:
  • Confusing stop with delete
  • Assuming restart keeps app stopped
  • Thinking delete crashes the app
4. You run pm2 start app.js but the app crashes immediately. Which PM2 command helps you see the error logs to debug the issue?
medium
A. pm2 status
B. pm2 logs
C. pm2 restart
D. pm2 list

Solution

  1. Step 1: Identify command to view logs

    pm2 logs shows real-time logs including errors from apps managed by PM2.
  2. Step 2: Compare other commands

    pm2 status and pm2 list show process info but not detailed logs. pm2 restart restarts apps but doesn't show logs.
  3. Final Answer:

    pm2 logs -> Option B
  4. Quick Check:

    Logs show errors for debugging [OK]
Hint: Use 'pm2 logs' to see app errors instantly [OK]
Common Mistakes:
  • Using 'pm2 status' to find errors
  • Restarting app without checking logs
  • Confusing 'pm2 list' with logs
5. You want PM2 to automatically restart your app server.js whenever the file changes during development. Which command achieves this?
hard
A. pm2 start server.js --watch
B. pm2 start server.js --no-restart
C. pm2 start server.js --ignore-watch
D. pm2 start server.js --restart-delay 1000

Solution

  1. Step 1: Understand PM2 watch option

    The --watch flag tells PM2 to watch for file changes and restart the app automatically.
  2. Step 2: Evaluate other options

    --no-restart disables restarts, --ignore-watch disables watching, and --restart-delay adds delay but doesn't enable watching.
  3. Final Answer:

    pm2 start server.js --watch -> Option A
  4. Quick Check:

    Watch flag enables auto-restart on file changes [OK]
Hint: Use '--watch' to auto-restart on file changes [OK]
Common Mistakes:
  • Using --no-restart disables restarts
  • Ignoring watch disables file monitoring
  • Restart delay doesn't watch files
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard