PM2 helps keep your Express app running smoothly. It restarts your app if it crashes and makes managing multiple app instances easy.
0
0
PM2 for process management in Express
Introduction
You want your Express server to restart automatically if it stops unexpectedly.
You need to run multiple copies of your app to handle more users.
You want to monitor your app's performance and logs easily.
You want to start your app automatically when your computer reboots.
You want a simple way to manage your app processes from the command line.
Syntax
Express
pm2 start app.js --name my-app
pm2 stop my-app
pm2 restart my-app
pm2 list
pm2 logs my-appUse pm2 start to launch your app with PM2.
The --name option helps you identify your app in PM2 commands.
Examples
Starts your Express app and names it my-express-app for easy management.
Express
pm2 start app.js --name my-express-app
Restarts the running app named my-express-app without downtime.
Express
pm2 restart my-express-app
Stops the app named my-express-app.
Express
pm2 stop my-express-app
Shows real-time logs of your app to help you see what is happening.
Express
pm2 logs my-express-app
Sample Program
This is a simple Express app that responds with a greeting. You can run it with PM2 to keep it running and manage it easily.
Express
const express = require('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}`); });
OutputSuccess
Important Notes
PM2 can run your app in cluster mode to use multiple CPU cores.
Use pm2 save to save your process list and pm2 startup to enable auto-start on reboot.
Check logs often with pm2 logs to catch errors early.
Summary
PM2 keeps your Express app running without manual restarts.
You can easily start, stop, and restart your app using simple commands.
PM2 helps monitor your app and manage multiple instances for better performance.