If you're a developer working with Node.js applications, you're likely familiar with PM2, a popular process manager. PM2 simplifies the deployment and management of Node.js processes, making it an essential tool for production environments. To help you navigate the world of PM2 more efficiently, here's a quick cheatsheet to reference:
Installation
# Install PM2 globally
npm install -g pm2
Basic Commands
- Start an application:
pm2 start app.js
- List running processes:
pm2 list
- Stop a process:
pm2 stop <app_name_or_id>
- Restart a process:
pm2 restart <app_name_or_id>
- Remove a process from the process list:
pm2 delete <app_name_or_id>
Advanced Commands
- Display detailed information about a process:
pm2 show <app_name_or_id>
- Monitor application CPU and memory usage:
pm2 monit
- View logs for a specific process:
pm2 logs <app_name_or_id>
- Save current process list:
pm2 save
- Generate startup script to keep processes alive across system reboots:
pm2 startup
Cluster Mode
PM2 can run multiple instances of an application in cluster mode, utilizing all available CPU cores. To start an application in cluster mode:
pm2 start app.js -i <num_instances>
Common Options
- Specify a process name:
pm2 start app.js --name <custom_name>
- Set environment variables:
pm2 start app.js --env production
- Set the number of restart attempts before giving up:
pm2 start app.js --max-restarts 3
Configuration File
Create a pm2.config.js
file to define configuration options for your application. Example:
module.exports = {
apps: [
{
name: 'my-app',
script: 'app.js',
watch: true,
env: {
NODE_ENV: 'development',
},
env_production: {
NODE_ENV: 'production',
},
},
],
};
Start your application using the configuration file:
pm2 start pm2.config.js
This cheatsheet provides a quick overview of essential PM2 commands, but there's much more to explore and customize based on your specific needs. Refer to the official documentation for a comprehensive guide. Happy coding!
Top comments (0)