0
0
Expressframework~15 mins

PM2 for process management in Express - Deep Dive

Choose your learning style9 modes available
Overview - PM2 for process management
What is it?
PM2 is a tool that helps you run and manage your Node.js applications easily. It keeps your app running all the time, restarts it if it crashes, and helps you control multiple app instances. Think of it as a manager that watches over your app to make sure it never stops working.
Why it matters
Without PM2, if your app crashes or your server restarts, your app would stop working until you manually start it again. This can cause downtime and unhappy users. PM2 solves this by automatically restarting your app and managing its processes, so your app stays online and reliable without you needing to watch it all the time.
Where it fits
Before learning PM2, you should know basic Node.js and how to run an Express app. After PM2, you can learn about advanced deployment tools, containerization like Docker, or cloud services that also manage app processes.
Mental Model
Core Idea
PM2 is like a smart supervisor that keeps your Node.js app running smoothly by managing its processes and restarting them if they fail.
Think of it like...
Imagine you own a bakery and hire a manager who watches the ovens. If an oven breaks, the manager quickly fixes or replaces it so baking never stops. PM2 is that manager for your app's processes.
┌─────────────┐      ┌─────────────┐      ┌─────────────┐
│  PM2 Tool   │─────▶│  App Process│─────▶│  User Request│
│ (Supervisor)│      │ (Oven)      │      │ (Customer)  │
└─────────────┘      └─────────────┘      └─────────────┘
       ▲                    │                    │
       │                    ▼                    ▼
       │             Restarts if crashes     Handles requests
       └───────────────────────────────────────────────┘
Build-Up - 7 Steps
1
FoundationWhat is PM2 and why use it
🤔
Concept: Introducing PM2 as a process manager for Node.js apps.
PM2 is a command-line tool that helps you start, stop, and monitor your Node.js applications. It keeps your app running even if it crashes or the server restarts. You install it globally using npm and then use simple commands to manage your app.
Result
You can run your Express app with PM2 and it will stay alive automatically.
Understanding that apps can crash or stop unexpectedly shows why a tool like PM2 is essential for real-world apps.
2
FoundationInstalling and starting an app with PM2
🤔
Concept: How to install PM2 and start an Express app using it.
Run 'npm install -g pm2' to install PM2 globally. Then, start your app with 'pm2 start app.js'. PM2 will launch your app and keep it running in the background. You can check running apps with 'pm2 list'.
Result
Your app runs under PM2 control and stays alive even if you close the terminal.
Knowing how to start and list apps with PM2 is the first step to managing processes effectively.
3
IntermediateManaging app restarts and crashes
🤔Before reading on: do you think PM2 restarts your app automatically after a crash or do you need to restart it manually? Commit to your answer.
Concept: PM2 automatically restarts your app if it crashes or stops unexpectedly.
If your Express app crashes due to an error, PM2 detects this and restarts it immediately. This means your app recovers without downtime. You can also manually restart apps with 'pm2 restart app_name'.
Result
Your app stays online with minimal interruption even after crashes.
Understanding automatic restarts helps you build more reliable apps without manual intervention.
4
IntermediateUsing PM2 to run multiple app instances
🤔Before reading on: do you think running multiple instances of your app with PM2 improves performance or just duplicates work? Commit to your answer.
Concept: PM2 can run multiple instances of your app to use all CPU cores and handle more users.
Use 'pm2 start app.js -i max' to run as many instances as CPU cores. PM2 balances user requests across these instances, improving app speed and reliability.
Result
Your app can handle more traffic by using all CPU cores efficiently.
Knowing how to scale your app with PM2 prepares you for handling real-world traffic spikes.
5
IntermediateMonitoring and logging with PM2
🤔
Concept: PM2 provides tools to watch app health and logs in real time.
Use 'pm2 monit' to see CPU and memory use of your app. Logs are stored and can be viewed with 'pm2 logs'. This helps you find problems and understand app behavior.
Result
You get real-time insight into your app’s performance and errors.
Monitoring is key to maintaining app health and quickly fixing issues.
6
AdvancedSaving and resurrecting process lists
🤔Before reading on: do you think PM2 remembers your running apps after a server reboot automatically or do you need to save the list? Commit to your answer.
Concept: PM2 can save the list of running apps and restore them after a reboot.
Run 'pm2 save' to save current processes. Then set up PM2 startup script with 'pm2 startup' so your apps start automatically when the server boots.
Result
Your apps restart automatically after server restarts without manual commands.
Knowing how to persist process lists ensures zero downtime even after server reboots.
7
ExpertUnderstanding PM2 internals and ecosystem
🤔Before reading on: do you think PM2 is just a simple script or a full-featured daemon with APIs? Commit to your answer.
Concept: PM2 runs as a background daemon managing processes and offers APIs and modules for advanced control.
PM2 runs a daemon process that manages your apps, handles clustering, and communicates via IPC. It supports modules like Keymetrics for monitoring and can be controlled programmatically. This design allows robust, scalable process management.
Result
You understand PM2 is a powerful system, not just a command-line tool.
Understanding PM2’s architecture helps you leverage its full power and integrate it into complex systems.
Under the Hood
PM2 runs a background daemon process that launches and monitors your Node.js app processes. It uses Node.js cluster module to run multiple instances and listens for process events like exit or error. When a process crashes, PM2 detects it and restarts the process automatically. It also manages logs and resource usage, exposing commands and APIs to control apps.
Why designed this way?
PM2 was designed to solve the problem of keeping Node.js apps alive in production, where crashes and server restarts are common. Using a daemon allows continuous monitoring independent of user terminals. Clustering uses all CPU cores efficiently. Alternatives like manual scripts or forever lacked features like clustering and easy monitoring, so PM2 became the standard.
┌─────────────┐        ┌───────────────┐        ┌───────────────┐
│   PM2 Daemon│───────▶│  App Processes│───────▶│  User Requests│
│ (Background)│        │ (Multiple Node)│        │ (Handled by   │
│             │        │               │        │  Instances)   │
└─────────────┘        └───────────────┘        └───────────────┘
       ▲                      ▲                        ▲
       │                      │                        │
       │                      │                        │
       │                      │                        │
       └─────────Monitors──────┴────Restarts on crash─┘
Myth Busters - 4 Common Misconceptions
Quick: Does PM2 automatically restart your app after a crash without any setup? Commit yes or no.
Common Belief:PM2 restarts apps automatically without any configuration needed.
Tap to reveal reality
Reality:PM2 restarts apps automatically only if you start them with PM2. If you run your app without PM2, it won't restart.
Why it matters:If you forget to start your app with PM2, you lose all benefits and your app can go down unnoticed.
Quick: Does running multiple PM2 instances always improve app speed? Commit yes or no.
Common Belief:Running many PM2 instances always makes the app faster.
Tap to reveal reality
Reality:Running multiple instances helps only if your app is CPU-bound and can handle parallel requests. For single-threaded or I/O-bound apps, it may not help and can add overhead.
Why it matters:Misusing clustering wastes resources and can degrade performance.
Quick: Is PM2 a replacement for a full deployment system? Commit yes or no.
Common Belief:PM2 alone is enough to deploy and manage production apps fully.
Tap to reveal reality
Reality:PM2 manages processes but does not handle code deployment, scaling across servers, or backups. It should be combined with deployment tools and infrastructure management.
Why it matters:Relying only on PM2 can lead to incomplete production setups and unexpected failures.
Quick: Does PM2 keep logs forever by default? Commit yes or no.
Common Belief:PM2 stores all logs indefinitely without limits.
Tap to reveal reality
Reality:PM2 logs grow over time and need manual rotation or cleanup to avoid disk space issues.
Why it matters:Ignoring log management can cause server storage to fill up and crash.
Expert Zone
1
PM2’s cluster mode uses Node.js cluster module but also manages inter-process communication and load balancing internally, which is more sophisticated than just spawning processes.
2
The PM2 daemon runs independently of your shell, so killing your terminal does not affect running apps, but improper shutdown of PM2 can leave orphan processes.
3
PM2 supports ecosystem files (JSON or JS) to define multiple apps and their environments, enabling complex multi-app setups with one command.
When NOT to use
PM2 is not ideal for serverless environments or containerized apps where process management is handled by the platform (like Kubernetes or Docker). In those cases, use native orchestration tools instead.
Production Patterns
In production, PM2 is often combined with reverse proxies like Nginx, log management systems, and monitoring dashboards (Keymetrics). Teams use ecosystem files for multi-app deployments and automate PM2 startup scripts for zero-downtime restarts.
Connections
Load Balancers
PM2’s clustering balances load across app instances similar to how load balancers distribute traffic across servers.
Understanding PM2 clustering helps grasp how load balancing works at different system layers.
Operating System Daemons
PM2 runs as a daemon process, similar to OS services that run in the background to manage tasks.
Knowing how OS daemons work clarifies why PM2 can keep apps alive independently of user sessions.
Factory Production Lines
PM2 managing multiple app instances is like a factory running several production lines to increase output and handle more orders.
This connection shows how parallelism and process management concepts apply beyond computing.
Common Pitfalls
#1Starting the app without PM2 and expecting it to restart automatically.
Wrong approach:node app.js
Correct approach:pm2 start app.js
Root cause:Misunderstanding that PM2 must launch the app to manage its lifecycle.
#2Running too many PM2 instances on a single-core CPU.
Wrong approach:pm2 start app.js -i 8
Correct approach:pm2 start app.js -i 1
Root cause:Not considering hardware limits leads to resource contention and poor performance.
#3Not saving the PM2 process list before reboot, causing apps not to restart automatically.
Wrong approach:pm2 start app.js # Reboot server # Apps do not restart
Correct approach:pm2 start app.js pm2 save pm2 startup # Reboot server # Apps restart automatically
Root cause:Forgetting to persist process list and configure startup scripts.
Key Takeaways
PM2 is a process manager that keeps your Node.js apps running by restarting them if they crash or stop.
It can run multiple instances of your app to use all CPU cores and handle more traffic efficiently.
PM2 runs as a background daemon independent of your terminal, providing monitoring and log management.
To ensure apps restart after server reboots, you must save the process list and configure startup scripts.
PM2 is a powerful tool but should be combined with deployment and infrastructure management for production.