How to Use PM2 in Node.js for Process Management
Use
pm2 to run and manage Node.js applications by installing it globally with npm install -g pm2, then start your app using pm2 start app.js. PM2 keeps your app alive, restarts it on crashes, and helps manage multiple processes easily.Syntax
PM2 basic commands:
pm2 start <file>: Starts your Node.js app.pm2 stop <id|name>: Stops a running app by its process id or name.pm2 restart <id|name>: Restarts the app.pm2 list: Shows all running processes managed by PM2.pm2 logs: Displays logs of your apps.
Each command helps you control your Node.js app processes easily.
bash
pm2 start app.js pm2 stop app pm2 restart app pm2 list pm2 logs
Example
This example shows how to start a simple Node.js app with PM2, check its status, and view logs.
javascript
/* app.js */ const http = require('http'); const port = 3000; const server = http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello from PM2 managed app!'); }); server.listen(port, () => { console.log(`Server running at http://localhost:${port}/`); });
Output
Server running at http://localhost:3000/
Common Pitfalls
Common mistakes when using PM2:
- Not installing PM2 globally, causing
pm2command not found. - Starting the app without specifying the correct file path.
- Forgetting to save the process list with
pm2 saveto restart on server reboot. - Not checking logs with
pm2 logsto debug issues.
Always verify your app path and use pm2 save after starting processes to keep them persistent.
bash
/* Wrong way: */ pm2 start /* Right way: */ pm2 start app.js pm2 save
Quick Reference
| Command | Description |
|---|---|
| pm2 start | Start a Node.js app |
| pm2 stop | Stop a running app |
| pm2 restart | Restart the app |
| pm2 list | List all managed processes |
| pm2 logs | Show app logs |
| pm2 save | Save process list for startup |
| pm2 startup | Generate startup script for server reboot |
Key Takeaways
Install PM2 globally with npm to use it anywhere.
Use pm2 start to run your Node.js app under PM2 management.
Check running apps with pm2 list and view logs with pm2 logs.
Save your process list with pm2 save to keep apps running after reboot.
Always verify your app path and monitor logs to avoid common errors.