Topic 54 of 55
PM2 Process Management
Overview
If a Node.js app crashes in production due to an error, it stops completely. PM2 is a production process manager that keeps your application alive forever by automatically restarting it if it crashes. It also provides logging and monitoring.
Syntax
bash
# Install PM2 globally on the server
npm install -g pm2
# Start an application (it runs in the background)
pm2 start app.js --name "my-api"
# View running applications
pm2 list
pm2 status
# View live logs
pm2 logs my-api
# Stop / Restart / Delete
pm2 stop my-api
pm2 restart my-api
pm2 delete my-apiCommon Pitfalls
- Never run `nodemon` in production. Nodemon is for development (restarting when files change). PM2 is for production (restarting when crashes occur).
- PM2 logs can grow infinitely and consume all disk space. Install the PM2 logrotate module: `pm2 install pm2-logrotate`.
Real-World Example
Ensuring PM2 restarts your app if the physical server reboots:
example
bash
# 1. Generate a startup script for your specific OS
pm2 startup
# (PM2 will output a command you need to copy and paste into the terminal)
# 2. Save the current list of running apps so they are restored on boot
pm2 save
# Now, if the AWS/DigitalOcean server loses power and reboots,
# PM2 will automatically launch your Node apps!