Deploying Node.js with PM2: Process Guarding and Cluster Mode
Running a Node.js app with plain node app.js in production means the service dies whenever the process crashes or the server reboots. PM2 is the process manager built to solve exactly that: it keeps the app running in the background, restarts it after crashes, boots it automatically, and can use cluster mode to fully utilize multiple CPU cores.
1. Installation and Startup
PM2 is installed globally via npm:
npm install -g pm2
pm2 start app.js --name my-api
pm2 start daemonizes and monitors the process in the background. Common commands:
pm2 list # view status of all processes
pm2 logs my-api # view logs
pm2 monit # real-time terminal monitoring dashboard
pm2 restart my-api # restart
pm2 stop my-api # stop
pm2 delete my-api # remove from PM2
Verify the install with pm2 -v; if your company network uses an npm mirror, configure the registry first to avoid install timeouts.
2. Cluster Mode: Making the Most of Multiple Cores
The default fork mode is a single process that uses only one CPU core. For HTTP/WS applications, use cluster mode to spawn multiple processes based on CPU count; PM2's built-in load balancer distributes connections automatically:
pm2 start app.js -i max # start one process per available CPU
pm2 scale app +3 # dynamically add 3 processes
How to choose between the two modes:
| Aspect | fork mode | cluster mode |
|---|---|---|
| Process count | 1 | spawned per CPU core |
| CPU usage | single core | multiple cores |
| Session stickiness | n/a | built-in load balancing |
| Best for | cron jobs, CLI tools | HTTP/WebSocket services |
For production, declaring this in a config file is recommended:
// ecosystem.config.js
module.exports = {
apps: [{
name: "api",
script: "./src/server.js",
instances: "max", // cluster mode, process count = CPU cores
exec_mode: "cluster",
max_memory_restart: "300M", // auto-restart above 300M
env: {
NODE_ENV: "production",
PORT: 3000
},
time: true // timestamp logs
}]
};
pm2 start ecosystem.config.js
max_memory_restart is very useful: it restarts a process automatically on memory leaks, buying time to investigate. For sensitive config, prefer an environment-variable file and combine it with environment variables and secret management — do not hard-code database passwords in the config.
3. Boot Persistence: pm2 startup and pm2 save
After a server reboot, PM2 needs to restore all processes. Two steps solve it:
pm2 startup # generate and install a startup script (it will prompt for a sudo command)
pm2 save # save the current process list, restored automatically at boot
pm2 startup generates the appropriate systemd unit for your system so PM2 and its managed processes start automatically at boot. Important: re-run pm2 save every time you add or remove a process, otherwise the next reboot restores the old process list.
4. Zero-Downtime Reload
A normal pm2 restart is "stop then start" and causes a brief interruption. For network applications in cluster mode, use pm2 reload for rolling restarts one process at a time, achieving zero downtime:
pm2 reload all # gracefully reload all processes
PM2 brings up the new process first and only switches over once old connections drain, which makes it ideal to call from the deployment script of an automated CI/CD deployment. For more systematic strategies see zero-downtime deployment strategies.
5. Log Management
PM2 writes stdout/stderr to logs by default and supports rotation:
pm2 logs my-api --lines 200 # view the last 200 lines
pm2 install pm2-logrotate # install the log rotation module
In production, consider feeding logs to a collection system and handling them together with ELK log analysis or monitoring and alerting.
6. Process Status Monitoring
pm2 monit provides real-time CPU/memory monitoring; pm2 describe <id> shows detailed process info. A sharply rising restart count is usually a signal of code crashes or memory leaks, and you can collect metrics with Prometheus and Grafana. Treat PM2 monitoring as the first line of defense: when something looks wrong, check pm2 monit and the restart count before diving into system-level investigation — it saves a lot of time.
- My processes disappeared after a reboot:Most likely
pm2 savewas never run, or the startup script was not installed. Re-runpm2 save, thenpm2 startuponce more. - Why does memory usage double in cluster mode:That is expected — each instance has its own memory space, so N instances roughly equal single-instance memory × N. Factor total memory in when sizing
max_memory_restart. - What if the port is taken:In cluster mode instances share one port by default, handled by PM2's built-in load balancer; if startup reports EADDRINUSE, check for leftover processes or an accidental fork mode.
7. A Complete Deploy Script
String the commands above together and you have a concise release script:
# deploy.sh
cd /srv/app
git pull origin main
npm ci --production
pm2 reload ecosystem.config.js # zero downtime
pm2 save # save the latest process list
On the first deploy run pm2 start ecosystem.config.js; afterwards, every release is just pm2 reload plus pm2 save.
8. Pairing with an Nginx Reverse Proxy
PM2 manages the Node process itself; external exposure should be handled by an Nginx reverse proxy: Nginx listens on 80/443, terminates TLS and forwards to the local port PM2 is listening on. For the non-LNMP Node stack see the Node.js Express guide; if your app also runs background job queues, manage them together with the background job queue guide. Placing the reverse proxy at the edge has another benefit: no matter how the Node processes scale or restart, the external address never changes, and clients and search engines never notice internal churn.
16IDC Note
PM2's value is solving the "liveness" problem of Node production processes at a tiny learning cost: guarding, restarting, boot persistence, clustering, logging and monitoring all in one tool. For independent sites and small teams, the pm2 start + pm2 startup + pm2 save triple makes the app run reliably in production, and combined with an Nginx reverse proxy and automated CI/CD it forms a complete, lightweight Node go-live solution.
Source: https://pm2.keymetrics.io/docs/usage/quick-start/ , https://pm2.keymetrics.io/docs/usage/process-management/
Reference: PM2 cluster mode docs https://pm2.keymetrics.io/docs/usage/cluster-mode/
Operation & Verification Steps
Example 1: Keep deployment parameters in ecosystem.config.js under version control
// ecosystem.config.js
module.exports = {
apps: [
{
name: 'web',
script: './server.js',
instances: process.env.PM2_INSTANCES || 2,
exec_mode: 'cluster',
autorestart: true,
max_memory_restart: '512M',
kill_timeout: 8000, // time for graceful shutdown on SIGTERM
wait_ready: true, // startup completes only after process.send('ready')
listen_timeout: 10000,
env: {
NODE_ENV: 'production',
PORT: 3000,
},
error_file: '/var/log/pm2/web-error.log',
out_file: '/var/log/pm2/web-out.log',
time: true, // timestamps in logs make ordering debuggable
},
],
};
instances sets the cluster width; exec_mode: 'cluster' makes PM2 use Node's native cluster module to share connections.
Example 2: Boot persistence plus a zero-downtime reload
# 1) Start with the production config
pm2 start ecosystem.config.js --env production
# 2) Generate and install the systemd/launchd boot unit (run the printed sudo command)
pm2 startup
# 3) Persist the process list so it comes back after a reboot
pm2 save
# 4) Every later release is just reload plus save
git pull && npm ci --omit=dev
pm2 reload ecosystem.config.js --env production && pm2 save
# 5) Check state and rotate logs
pm2 ls && pm2 describe web | head -20
pm2 install pm2-logrotate # once only, so logs do not fill the disk
Use reload, not restart: it replaces workers one by one, and with wait_ready you keep serving traffic during the release.
Limitations
- This article reflects public information as of 2026-08-06; terms, prices and quotas follow the provider's current published terms.
- Third-party capability and limit statements follow their official documentation; no further commitment is implied here.
- Licensing, filing and data-residency decisions must be verified against the regulations of your operating region.
FAQ
What does pm2 startup require on the host?
Global write access for npm plus a host running systemd. pm2 startup writes a unit file and prints a sudo command you run once, and the saved process list is only restored on boot after pm2 save. Containers usually lack systemd, so boot persistence has to come from the orchestrator instead.
Why does the restart counter keep climbing?
Check the restart count and memory peak in pm2 describe first. A number that keeps rising usually means a crash loop or a leak, so compare it with the max_memory_restart threshold such as 512M. Exit codes in pm2 logs separate an application exception from an OOM kill.
Should the database secret live in ecosystem.config.js?
No — keep only the key name there and read values from the environment. That file is committed with the code, so a plaintext password is visible to everyone with repository access. Put the connection string in an env file or the platform secret store, then pm2 reload so workers pick up the new value one by one.
Does PM2 replace Nginx in a Node stack?
No, they sit at different layers. Nginx listens on 80/443, terminates TLS and proxies to the local port, while PM2 only keeps processes alive and spreads them across cores. A bare systemd unit can also start the app on boot, but it has no rolling reload or memory-threshold restart.
Related Providers
- Node.js: check the LTS line and known issues when cluster mode behaviour under PM2 has to be confirmed for a target version.
- GitHub Actions: keep SSH keys and restart steps in one workflow when every push should trigger a pm2 reload.
Community & Resources
-
Environment Deployment: other coverage in this category.
Official docs and communities -
PM2 application declaration — Official reference for every
ecosystem.config.jsfield. -
PM2 startup docs — Correct usage of
pm2 startupandpm2 save. -
PM2 cluster mode — How cluster mode works and how to size it.
-
Node.js cluster module — The native capability PM2 cluster mode builds on.
Learning resources and tools
- PM2 on GitHub — Source, issues and release history.
- PM2 log management — Official guidance on log files, rotation and aggregation.
- PM2 graceful reload — How graceful shutdown pairs with
wait_ready. - Express documentation — Docs for the Node web framework most often run under PM2.
Original source: PM2 Docs ↗