How to Use PM2 for Production in Node.js: Simple Guide
Use
pm2 start app.js to run your Node.js app in production with PM2. PM2 keeps your app alive, restarts it on crashes, and lets you manage logs and processes easily with commands like pm2 status and pm2 logs.Syntax
PM2 commands help you start, monitor, and manage Node.js apps in production.
pm2 start <file>: Starts your app and keeps it running.pm2 stop <id|name>: Stops a running app.pm2 restart <id|name>: Restarts the app, useful after code changes.pm2 status: Shows the list of running apps and their status.pm2 logs: Displays real-time logs of your apps.pm2 save: Saves the current process list for automatic startup on server reboot.pm2 startup: Generates and configures startup scripts to launch PM2 and your apps on system boot.
bash
pm2 start app.js pm2 status pm2 logs pm2 restart app pm2 stop app pm2 save pm2 startup
Example
This example shows how to start a simple Node.js app with PM2, check its status, view logs, and set it to restart on server reboot.
javascript
const http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello from PM2 managed app!'); }); server.listen(3000, () => { console.log('Server running on port 3000'); });
Output
Server running on port 3000
Common Pitfalls
Common mistakes when using PM2 in production include:
- Not saving the process list with
pm2 save, so apps don't restart after reboot. - Forgetting to run
pm2 startupto configure auto-start on system boot. - Running PM2 without a process file or ecosystem config for complex apps, making management harder.
- Ignoring logs; always check
pm2 logsto debug crashes.
bash
/* Wrong: Starting app but not saving or setting startup */ pm2 start app.js /* Right: Save and setup startup for production */ pm2 start app.js pm2 save pm2 startup
Quick Reference
| Command | Purpose |
|---|---|
| pm2 start | Start and daemonize your Node.js app |
| pm2 stop | Stop a running app |
| pm2 restart | Restart app after changes |
| pm2 status | Show running apps and their status |
| pm2 logs | View real-time logs |
| pm2 save | Save current process list for reboot |
| pm2 startup | Generate startup script for auto-launch |
Key Takeaways
Use pm2 start to run your Node.js app in production and keep it alive.
Always run pm2 save and pm2 startup to ensure your app restarts after server reboot.
Check pm2 logs regularly to catch and fix errors quickly.
Use pm2 status to monitor your app's health and running state.
For complex apps, consider using a pm2 ecosystem.config.js file for easier management.