DEV Community

Manthan Ankolekar
Manthan Ankolekar

Posted on

PM2 Cheatsheet: A Quick Reference Guide

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
Enter fullscreen mode Exit fullscreen mode

Basic Commands

  • Start an application:
  pm2 start app.js
Enter fullscreen mode Exit fullscreen mode
  • List running processes:
  pm2 list
Enter fullscreen mode Exit fullscreen mode
  • Stop a process:
  pm2 stop <app_name_or_id>
Enter fullscreen mode Exit fullscreen mode
  • Restart a process:
  pm2 restart <app_name_or_id>
Enter fullscreen mode Exit fullscreen mode
  • Remove a process from the process list:
  pm2 delete <app_name_or_id>
Enter fullscreen mode Exit fullscreen mode

Advanced Commands

  • Display detailed information about a process:
  pm2 show <app_name_or_id>
Enter fullscreen mode Exit fullscreen mode
  • Monitor application CPU and memory usage:
  pm2 monit
Enter fullscreen mode Exit fullscreen mode
  • View logs for a specific process:
  pm2 logs <app_name_or_id>
Enter fullscreen mode Exit fullscreen mode
  • Save current process list:
  pm2 save
Enter fullscreen mode Exit fullscreen mode
  • Generate startup script to keep processes alive across system reboots:
  pm2 startup
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Common Options

  • Specify a process name:
  pm2 start app.js --name <custom_name>
Enter fullscreen mode Exit fullscreen mode
  • Set environment variables:
  pm2 start app.js --env production
Enter fullscreen mode Exit fullscreen mode
  • Set the number of restart attempts before giving up:
  pm2 start app.js --max-restarts 3
Enter fullscreen mode Exit fullscreen mode

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',
      },
    },
  ],
};
Enter fullscreen mode Exit fullscreen mode

Start your application using the configuration file:

pm2 start pm2.config.js
Enter fullscreen mode Exit fullscreen mode

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)