PM2 helps keep your Node.js apps running smoothly. It restarts apps if they crash and makes managing multiple apps easy.
0
0
PM2 for process management in Node.js
Introduction
You want your Node.js app to restart automatically if it crashes.
You need to run multiple Node.js apps at the same time.
You want to monitor app performance and logs easily.
You want to start your app automatically when the server boots.
You want to manage app versions and reload without downtime.
Syntax
Node.js
pm2 start <app.js> [options]
pm2 stop <app_name_or_id>
pm2 restart <app_name_or_id>
pm2 list
pm2 logs
pm2 monitUse pm2 start to launch your app with PM2.
App can be referenced by name or ID for stop/restart commands.
Examples
Starts the app.js file with PM2.
Node.js
pm2 start app.js
Restarts the app with ID 0.
Node.js
pm2 restart 0Stops the app named 'my-app'.
Node.js
pm2 stop my-app
Shows all running apps managed by PM2.
Node.js
pm2 listSample Program
This simple Node.js app creates a server that responds with a greeting. You can run it with PM2 to keep it running and restart if it crashes.
Node.js
/* 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 on port ${port}`); });
OutputSuccess
Important Notes
PM2 can save app states and resurrect them after server reboot using pm2 save and startup scripts.
Use pm2 logs to see real-time logs of your apps.
PM2 also supports cluster mode to use multiple CPU cores for better performance.
Summary
PM2 keeps Node.js apps running and restarts them if they crash.
You can manage multiple apps easily with simple commands.
It helps monitor apps and handle server restarts smoothly.