DeveloperBreeze

PM2 Installation

npm install pm2@latest -g

Process Management

Start an application

pm2 start app.js
  • Start your app as a process managed by PM2.

Start an app with a name

pm2 start app.js --name "app-name"

Start an app on a specific port

pm2 start app.js --name "app-name" -- 3000

Start an app in cluster mode (multi-core support)

pm2 start app.js -i max
  • -i max starts as many instances as there are CPU cores.

Start app and watch for changes (useful for development)

pm2 start app.js --watch
  • Automatically restarts the app when changes are detected.

Stop an application

pm2 stop <app_name_or_id>

Restart an application

pm2 restart <app_name_or_id>

Delete an application

pm2 delete <app_name_or_id>

List running applications

pm2 list

Show details of a specific process

pm2 show <app_name_or_id>

Reload all applications (Zero Downtime Reload)

pm2 reload all

Start all previously stopped applications

pm2 start all

Logs and Monitoring

View logs of all apps

pm2 logs

View logs of a specific app

pm2 logs <app_name_or_id>

View real-time CPU/Memory usage of all apps

pm2 monit

Flush logs (clear logs for all apps)

pm2 flush

Reload logs (without restarting apps)

pm2 reloadLogs

Environment Variables

Start app with environment variables

pm2 start app.js --env production
  • The environment variables are defined in ecosystem.config.js or can be provided inline.

Start app with inline environment variables

pm2 start app.js --env VAR=value

Configuration Files

Use ecosystem.config.js for configuration (recommended)

  1. Create ecosystem.config.js:
   module.exports = {
     apps: [
       {
         name: 'app-name',
         script: 'app.js',
         instances: 'max',
         exec_mode: 'cluster',
         env: {
           NODE_ENV: 'development',
         },
         env_production: {
           NODE_ENV: 'production',
         }
       }
     ]
   };
  1. Start all apps in the config:
   pm2 start ecosystem.config.js
  1. Start with a specific environment:
   pm2 start ecosystem.config.js --env production

Startup and Auto-Restart

Generate startup script (persistent after reboot)

pm2 startup
  • Follow the instructions provided to enable PM2 on system startup.

Save the current process list

pm2 save
  • Save the list of running apps for auto-respawn after system restart.

Resurrection (restore apps after system reboot)

pm2 resurrect

Reset all processes

pm2 reset

Process Management for Microservices

Scale app horizontally

pm2 scale <app_name_or_id> <number_of_instances>

Limit memory usage for an app

pm2 start app.js --max-memory-restart 300M
  • Auto-restart when memory usage exceeds the limit.

Monitoring and Logs Management

Inspect logs for CPU or memory overuse

pm2 logs --lines 100
  • Shows the last 100 lines of logs for all apps.

Enable detailed log rotation (automatically rotate logs)

  1. Install the module:
   pm2 install pm2-logrotate
  1. Configure the log rotation:
   pm2 set pm2-logrotate:max_size 10M
   pm2 set pm2-logrotate:retain 30

Reloading and Zero Downtime

Zero downtime reload for production apps

pm2 reload <app_name_or_id>

Reload all apps with zero downtime

pm2 reload all

Miscellaneous Commands

Kill all processes managed by PM2

pm2 kill

Uninstall PM2 log rotation module

pm2 uninstall pm2-logrotate

Display memory and CPU usage

pm2 describe <app_name_or_id>

Get app metadata

pm2 env <app_name_or_id>

Cloning & Running App Across Multiple Servers

Run a command across all machines

pm2 deploy ecosystem.config.js production exec "npm install"

Update the app on all servers

pm2 deploy ecosystem.config.js production update

Deploy the app (via SSH)

  1. Define ecosystem.config.js:
   module.exports = {
     apps: [
       {
         name: 'app-name',
         script: 'app.js',
         env: {
           NODE_ENV: 'development',
         },
         env_production: {
           NODE_ENV: 'production',
         }
       }
     ],
     deploy: {
       production: {
         user: 'username',
         host: 'your-server.com',
         ref: 'origin/master',
         repo: 'git@github.com:your-repo.git',
         path: '/var/www/your-app',
         'post-deploy': 'npm install && pm2 reload ecosystem.config.js --env production',
       }
     }
   };
  1. Deploy your app:
   pm2 deploy ecosystem.config.js production
  1. Rollback:
   pm2 deploy ecosystem.config.js production revert 1

PM2 Health Checks

Check if PM2 is running

pm2 ping

Check version of PM2

pm2 -v

Continue Reading

Discover more amazing content handpicked just for you

Tutorial

How to Stop SSH From Timing Out

Restart SSH:

sudo systemctl restart sshd

Aug 21, 2025
Read More
Cheatsheet

ShadCN Cheatsheet

ShadCN doesn’t include tests by default. Use:

  • @testing-library/react
  • vitest or jest

Apr 12, 2025
Read More
Tutorial

🛡️ Protect Your Forms Like a Pro: Anti-Spam Techniques That Actually Work

In this tutorial, you'll learn real-world, effective anti-spam techniques beyond just slapping on a CAPTCHA. These strategies are easy to implement, and when combined, they make your forms extremely hard to abuse.

Before we dive in, it's important to know: most spammers use scripts, not humans. These bots scan for forms, autofill fields, and send POST requests rapidly—sometimes thousands per hour.

Apr 04, 2025
Read More
Tutorial

Build a Custom Rate Limiter in Node.js with Redis

mkdir node-rate-limiter
cd node-rate-limiter
npm init -y
npm install express redis dotenv

Create a .env file:

Apr 04, 2025
Read More
Cheatsheet
css html

Grids Cheatsheet

<!-- Basic grid container -->
<div class="container">
<div class="container-fluid">                     <!-- Full-width container -->

<!-- Row -->
<div class="row">                                 <!-- Basic row -->
<div class="row g-3">                             <!-- Row with gap -->

<!-- Responsive behavior -->
<div class="row row-cols-1">                      <!-- 1 column -->
<div class="row row-cols-md-2">                   <!-- 2 columns on md screens -->
<div class="row row-cols-lg-3">                   <!-- 3 columns on lg screens -->
<!-- Basic columns -->
<div class="col">                                 <!-- Equal width -->
<div class="col-6">                               <!-- 6/12 width -->
<div class="col-auto">                            <!-- Content-width -->

<!-- Responsive columns -->
<div class="col-sm-6">                           <!-- 6/12 on small screens -->
<div class="col-md-4">                           <!-- 4/12 on medium screens -->
<div class="col-lg-3">                           <!-- 3/12 on large screens -->

<!-- Column ordering -->
<div class="order-1">                            <!-- Order first -->
<div class="order-last">                         <!-- Order last -->

<!-- Offset -->
<div class="offset-md-3">                        <!-- Offset by 3 columns -->

<!-- Alignment -->
<div class="align-self-start">
<div class="align-self-center">
<div class="align-self-end">

Jan 14, 2025
Read More
Tutorial

How To view tables and the number of records in each table in a PostgreSQL database,

   \dt

Run the following SQL query to see the list of tables along with their row counts:

Nov 06, 2024
Read More
Tutorial

How to install PostgreSQL

   psql --version
  • Open the psql command line interface from the Start menu or use:

Nov 06, 2024
Read More
Tutorial

How to view tables on a PostgreSQL database hosted on Heroku

Open your database client, such as pgAdmin or DataGrip, and enter the details from the DATABASE_URL:

  • Host: Found in the URL after @
  • Database: Found after the last /
  • User and Password: Found between // and @
  • Port: Default is 5432 (or whatever is in the URL)

Nov 06, 2024
Read More
Tutorial

How to view your Heroku Apps

To view your Heroku apps, you can use either the Heroku CLI or the Heroku Dashboard.

Make sure you’re logged in to the Heroku CLI by running:

Nov 06, 2024
Read More
Cheatsheet
python

Python List Operations Cheatsheet

my_list = ["apple", "banana"]
my_list.extend(["cherry", "orange"])
print(my_list)  # Output: ['apple', 'banana', 'cherry', 'orange']
my_list = ["apple", "banana", "cherry"]
my_list.remove("banana")
print(my_list)  # Output: ['apple', 'cherry']

Oct 24, 2024
Read More
Tutorial

Understanding `crypto.randomBytes` and `ethers.randomBytes`: A Comparison

No preview available for this content.

Oct 24, 2024
Read More
Tutorial

Working with `BigNumber` in ethers.js: A Guide for Version 6

  • Subtraction:
  const result = num1.sub(num2);

Oct 24, 2024
Read More
Tutorial

Connecting a Node.js Application to an SQLite Database Using sqlite3

Expected Output:

Connected to the SQLite database.

Oct 24, 2024
Read More
Cheatsheet

Essential dpkg Commands Cheat Sheet for Debian and Ubuntu Systems

  • What it is: APT (Advanced Package Tool) is a higher-level front-end that interacts with dpkg and handles package relationships, dependencies, and versioning.
  • Why use APT: It simplifies the installation and removal of packages, ensuring that dependencies are correctly resolved.

Example for installing a package with APT:

Oct 24, 2024
Read More
Tutorial

Clearing Unnecessary Logs on Ubuntu

sudo reboot
  • Backup Logs: Before deleting, consider backing up important logs for future troubleshooting.
  • Avoid Deleting Critical Logs: Be cautious when removing logs that are essential for security and system diagnostics, such as auth.log, syslog, and kern.log.

Oct 24, 2024
Read More
Tutorial

Getting Started with DevSecOps — Secure CI/CD Pipelines with Jenkins

Security unit tests and API tests should also be part of your CI/CD pipeline.

stage('Run Unit and Security Tests') {
    steps {
        // Run unit tests
        sh 'mvn test'

        // You can also integrate security testing tools like ZAP or Gauntlt here
    }
}

Oct 22, 2024
Read More
Cheatsheet

Best Tools for Generating Backgrounds Patterns for Your Website

  • Website: Subtle Patterns
  • Features:
  • A massive collection of subtle and repeatable background patterns.
  • Free to use and download.
  • Patterns are perfect for minimalistic and elegant design aesthetics.
  • Best For: Web designers looking for ready-to-use, subtle background patterns to enhance user experience without overwhelming the design.
  • Website: Coolors
  • Features:
  • Known for its excellent color palette generator, Coolors also provides the ability to generate patterns.
  • Choose colors, add gradients, or even create geometric patterns.
  • Perfect for creating both color schemes and patterns in one place.
  • Best For: Designers who need both color palette inspiration and pattern creation in a single tool.

Oct 21, 2024
Read More
Tutorial
bash

How to Install and Configure Apache on Ubuntu

Available applications:
  Apache
  Apache Full
  Apache Secure
  OpenSSH

To allow both HTTP and HTTPS traffic, run:

Oct 21, 2024
Read More
Tutorial
bash

How to Create SSL for a Website on Ubuntu

Certbot is the client tool that will manage SSL certificate generation for Let's Encrypt. Depending on your web server (Apache or Nginx), install Certbot and the appropriate plugin.

sudo apt install certbot python3-certbot-apache

Oct 21, 2024
Read More
Tutorial
bash

How to Install MongoDB Shell (mongosh) on Ubuntu

wget https://downloads.mongodb.com/compass/mongosh-1.10.1-linux-x64.tgz

Extract the contents of the downloaded file using the tar command:

Oct 18, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!