How to use PM2 for process management
· Category: Node.js
Short answer
PM2 is a production process manager for Node.js that handles clustering, zero-downtime deployments, logging, and automatic restarts.
Steps
- Install PM2 globally:
npm install -g pm2. - Start your app:
pm2 start app.js --name my-app. - Enable cluster mode:
pm2 start app.js -i max. - Monitor processes:
pm2 monitorpm2 status. - Save and configure startup scripts with
pm2 startupandpm2 save.
Tips
- Use an ecosystem file (
ecosystem.config.js) to define environment variables, instances, and restart policies. - PM2 logs can be aggregated and rotated automatically.
Common issues
- Without
pm2 save, processes will not restart after a system reboot. - Cluster mode requires stateless apps because workers do not share in-memory data.