How to Use PM2 with Express for Node.js App Management
To use
pm2 with an Express app, first install PM2 globally using npm install -g pm2. Then start your Express server with pm2 start app.js to run it as a managed process that restarts on crashes and can be monitored easily.Syntax
Use pm2 start <file> to launch your Express app. PM2 runs the app as a background process, restarts it if it crashes, and lets you manage it with commands.
pm2 start app.js: Starts the Express app fileapp.js.pm2 list: Shows all running PM2 processes.pm2 stop <id|name>: Stops a running process.pm2 restart <id|name>: Restarts a process.pm2 logs: Shows logs of all processes.
bash
pm2 start app.js
pm2 list
pm2 stop 0
pm2 restart app
pm2 logsExample
This example shows a simple Express server started with PM2. PM2 keeps the server running in the background and restarts it if it crashes.
javascript
import express from 'express'; const app = express(); const PORT = 3000; app.get('/', (req, res) => { res.send('Hello from Express with PM2!'); }); app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); });
Output
Server running on http://localhost:3000
Common Pitfalls
1. Not installing PM2 globally: PM2 must be installed globally with npm install -g pm2 to use it from the command line.
2. Forgetting to use pm2 start: Running node app.js won't use PM2 features like auto-restart.
3. Not saving PM2 process list: Use pm2 save to keep your process list for system restarts.
bash
Wrong: node app.js Right: npm install -g pm2 pm2 start app.js pm2 save
Quick Reference
| Command | Description |
|---|---|
| pm2 start app.js | Start Express app with PM2 |
| pm2 list | List all PM2 managed processes |
| pm2 stop | Stop a running process |
| pm2 restart | Restart a process |
| pm2 logs | View logs of all processes |
| pm2 save | Save process list for auto-start on reboot |
Key Takeaways
Install PM2 globally to manage your Express app processes easily.
Use pm2 start to run your Express server with automatic restarts.
Save your PM2 process list to keep apps running after system reboots.
Use pm2 logs to monitor your app output and errors in real time.
Avoid running Express with node directly if you want process management.