Alerty Blog

A Guide on Node Pm2 Process Management and Optimization

Written by Jack Dwyer | Aug 2, 2024 3:01:59 PM

Ever wonder how to manage Node.js applications effectively in a production environment? Imagine your Node.js application crashes unexpectedly, and you struggle to identify the root cause in a log file. Understanding Node.js process management with Pm2 can significantly enhance your applications' performance and uptime. 

Alerty's Nodejs logging service offers focused support for Node.js process monitoring and management with Pm2, helping you optimize performance and reliability.

Table of Contents

What Is PM2?

PM2 is a popular process manager for Node.js applications, designed to help developers manage and optimize their server-side JavaScript code. Its primary purpose is to ensure that your Node.js applications run smoothly and efficiently by handling various aspects of process management. PM2 offers key features, including:

  • Process management
  • Monitoring
  • Clustering

With PM2, you can quickly:

PM2: Your Node.js App's Guardian Angel

This means your application can handle more traffic and run more reliably, with built-in tools to keep everything running smoothly and help you quickly identify and fix issues. PM2 acts like a robust toolkit that helps keep your Node.js apps performing at their best, providing peace of mind and better performance.

Related Reading

Why Use Pm2 for Node?

PM2 for Node.js enables you to keep applications alive forever. It also helps reload PM2 Node.js applications without downtime, manage application logging and monitoring, and configure PM2 for Node.js load balancing and clustering.

Here are the core features:

  • Process management, including automatic app restarts on failure or system reboots.
  • Managing environment variables in Node.js with PM2
  • Application monitoring
  • Declarative configuration via JSON file
  • PM2 Logs management
  • Built-in cluster mode
  • Startup script generation for nix systems
  • Seamless updates
  • Integrated module system

Alerty: Your All-in-One Cloud Monitoring Solution

Alerty is a cloud monitoring service for developers and early-stage startups, offering:

  • Application performance monitoring
  • Database monitoring
  • Incident management

It supports technologies like NextJS, React, Vue, and Node.js, helping developers identify and fix issues. 

  • Alerty monitors databases such as Supabase, PostgreSQL, and RDS
  • Tracking key metrics like CPU usage and memory consumption
  • It features quick incident management and Real User Monitoring (RUM) to optimize user experience
  • Its universal service monitoring covers dependencies like Stripe API, OpenAI, and Vercel 

Alerty uses AI to simplify setup, providing a cost-effective solution compared to competitors. It is designed for ease of use, allowing quick setup, and integrates with tools like Sentry, making it ideal for developers and small teams needing efficient, affordable monitoring. 

Catch issues before they affect your users with Alerty's NodeJS logging solution today!

Installing and Setting Up Pm2

Installing PM2 is a simple process that can be done through npm. First, open your terminal or command prompt and run the following command to install PM2 globally:

bash
npm install -g pm2

This command will download and install PM2, making it available system-wide. Once the installation is complete, you can verify that PM2 is installed correctly by checking its version with the following command:

bash
pm2 --version

This command will return the version number of PM2, confirming that it is installed and accessible.

Aside from the main `pm2` command, the installation also provides other executables like `pm2-dev` and `pm2-runtime`, which offer additional functionalities for development and runtime scenarios.

Basic Node Pm2 Commands and Usage

Starting Applications With PM2

To kick off your Node.js application, simply use the `pm2 start` command followed by the path to your application file. This command launches your application and maintains it running in the background, even if you close the terminal. Not only that, but PM2 also keeps track of your app's logs and status, ensuring you keep all critical information.

Managing Process Lists and Checking Status

To obtain a comprehensive overview of all processes managed by PM2, use the command `pm2 list`. This command will display a comprehensive overview of your applications, including:

  • IDs
  • Statuses
  • Resource usage

Deploy the command' pm2 status' to view the status information, including recent logs and errors. This command provides a more granular view of each process's current state and performance metrics.

Stopping and Restarting Applications

If you need to halt a running application, leverage the `pm2 stop` command followed by the application name or ID. Alternatively, you can stop an app using its PM2 ID, which you can readily find in the output of `pm2 list`. In contrast, you can deploy the simple command `pm2 restart app.js` to restart an application. This command is handy for incorporating code changes or troubleshooting issues without having to stop and start the application again manually.

By mastering these commands, you can efficiently manage your applications with PM2. PM2 enables you to quickly:

  • Start
  • Monitor
  • Control your Node.js processes

It undoubtedly simplifies the entire process, making Node.js application management a breeze.

Advanced PM2 Features

Monitoring and Troubleshooting with PM2

Regarding NodeJS logging and monitoring, PM2 offers robust features to help developers manage and monitor their applications effectively.

Viewing Running Applications

PM2 lets you quickly see all the applications currently managed by PM2 using the `pm2 list` command. This command provides a snapshot of your running processes, showing them:

  • Status
  • Memory usage
  • CPU usage
  • Other relevant information

With this information, you can quickly identify performance issues or potential bottlenecks.

Viewing Logs

Logs are essential for troubleshooting issues, and PM2 makes it easy to access and view logs for your applications. You can view logs in real-time using the `pm2 logs` command, which displays output from both the standard output (stdout) and standard error (stderr) streams for all applications. If you need to view logs for a specific application, you can specify the app name or ID, making it easy to pinpoint any issues affecting that application.

Your Node.js App's Historical Record Keeper

PM2 also enables you to access older logs, making it convenient to review historical data. By default, PM2 retains a certain number of log files, and you can specify how many lines of logs you want to see using the `--lines` option. This feature is useful when investigating past issues or tracking changes over time.

Monitoring Resource Usage

To get insights into the resource usage of your applications, PM2 includes a built-in monitoring tool that provides real-time metrics for all running applications. Using the `pm2 monit` command, you can open an interactive monitoring dashboard that displays CPU and memory utilization and other performance indicators. This dashboard helps you identify applications consuming excessive resources or experiencing performance issues, allowing you to take corrective action promptly.

Clustering

Another advanced feature of PM2 is its clustering capability, which enables load balancing and performance optimization by running multiple instances of your application across different CPU cores. By starting your application in cluster mode with the `-i max` option, PM2 creates as many instances as there are CPU cores, enhancing performance and enabling your application to handle more concurrent requests effectively. This setup ensures better load distribution and higher availability, making the most of multi-core systems.

Configuration

PM2 simplifies the management of complex application setups with ecosystem files, allowing you to define how your applications should be:

  • Started
  • Monitored
  • Scaled

Key Settings in `ecosystem.config.js`

  • Instances: Define the number of application instances to run.
  • Execution Mode: Choose between different modes, such as fork or cluster.
  • Environment Variables: Set environment variables to streamline the deployment process

Starting applications using this configuration file makes it easy to manage multiple applications and their settings from a single location, enhancing scalability, reliability, and maintainability.

By leveraging these advanced features, you can enhance the:

  • Scalability
  • Reliability
  • Maintainability of your Node.js applications, making PM2 a versatile tool for both simple and complex deployment scenarios.

Related Reading

Integrating PM2 With Deployment Pipelines

Automating PM2 with CI/CD Tools

Integrating PM2 with CI/CD tools like GitHub Actions and Jenkins can help streamline the deployment process and automate application updates. You can set up workflows that install PM2, deploy your Node.js application, and start it using the specified configuration.

Example: GitHub Actions

With GitHub Actions, a workflow file can be created to handle the deployment process. The workflow installs PM2, deploys your application, and starts it with the ecosystem configuration.

yaml
name: Deploy

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v2

      - name: Set up Node.js
        uses: actions/setup-node@v2
        with:
          node-version: '14'

      - name: Install dependencies
        run: npm install

      - name: Install PM2
        run: npm install -g pm2

      - name: Start application with PM2
        run: pm2 start ecosystem.config.js

Example: Jenkins

A pipeline script can automate PM2 tasks for Jenkins. The pipeline script checks your code, installs dependencies, and deploys the application using PM2.

groovy
pipeline {
  agent any

  stages {
    stage('Checkout') {
      steps {
        git 'https://github.com/your-repo.git'
      }
    }

    stage('Install Dependencies') {
      steps {
        sh 'npm install'
        sh 'npm install -g pm2'
      }
    }

    stage('Deploy') {
      steps {
        sh 'pm2 start ecosystem.config.js'
      }
    }
  }

  post {
    always {
      archiveArtifacts artifacts: '**/logs/*.log', allowEmptyArchive: true
      junit '**/test-results/*.xml'
    }
  }
}

Examples of Integration with Popular Deployment Services

Integrating PM2 with popular deployment services like Heroku and AWS Elastic Beanstalk can simplify the deployment process. A Procfile for Heroku can define how your application should be started using PM2. Similarly, a Procfile can be included for AWS Elastic Beanstalk to use PM2 to manage your Node.js application.

By integrating PM2 with CI/CD pipelines and deployment services, you can automate and streamline the management of your Node.js applications, ensuring smoother updates and more reliable performance.

Best Practices And Security Considerations

How to Prevent Downtime with Cluster Mode in PM2

Cluster mode runs multiple instances of your application to avoid downtime when a restart is required. This feature is handy to ensure continuous service during restarts. PM2 allows other instances to continue serving your application by restarting only one instance at a time.

Preparing Your Application for Cluster Mode

  • Before switching to cluster mode, stop the application to avoid any issues. 
  • Use the command `pm2 stop app` to do so. 
  • After stopping the application, start it in cluster mode by specifying the number of instances you want with the `-i' parameter. For instance, `pm2 start app.js -i 3` starts three instances of your application. 
  • If you need to scale up or down, use the `pm2 scale app 4` command to specify a new number of instances.

How To Eliminate Failed Requests With Graceful Shutdown in PM2

Graceful shutdowns allow your application to complete all tasks before it exits, helping to eliminate failed requests. To enable a graceful shutdown in PM2, follow these steps:

1. PM2 sends a SIGINT signal to your application before the shutdown process.
2. Your application intercepts the signal and starts to wrap up tasks.
3. Once all tasks are completed, such as handling HTTP requests and closing database connections, your application exits gracefully.

To demonstrate this, add a code snippet like the following in your application to handle the SIGINT signal gracefully:

javascript
process.on('SIGINT', function() {
    console.log('Shutdown signal intercepted');
    server.close();
    process.exit();
});

By incorporating these best practices, such as cluster mode and graceful shutdowns, you can enhance the performance and reliability of your Node.js applications managed by PM2.

Catch Issues Before They Affect Your Users With Alerty's NodeJS Logging Tool

Alerty is a game-changer in cloud monitoring services, particularly for developers and early-stage startups. It provides a comprehensive suite of services, including:

  • Application Performance Monitoring
  • Database Monitoring
  • Incident Management

Alerty caters to a vast array of technologies, offering support for NextJS, React, Vue, and Node.js, making it a versatile solution for many developers. 

Key Features

  • Database Monitoring: Tracks essential metrics for Supabase, PostgreSQL, and RDS.
  • Performance Metrics: Monitors CPU usage and memory consumption to identify potential issues.
  • Incident Management: Offers quick incident management features.
  • Real User Monitoring (RUM): Enhances the overall user experience.


Alerty’s Universal Service Monitoring covers critical dependencies like the Stripe API, OpenAI, and Vercel. This broad coverage ensures that developers can monitor and manage all aspects of their applications, streamlining the development and troubleshooting process. 

Advantages of Using Alerty

  • AI-Enhanced Setup: Simplifies the setup process for quick and efficient deployment.
  • Cost-Effective Solution: Offers a budget-friendly option compared to competitors, ideal for early-stage startups and small teams.
  • Integration with Tools: Enhances usability and efficiency by integrating with tools like Sentry.
  • Efficient Monitoring: Provides an effective and affordable monitoring solution for developers.


Get the most out of Alerty's NodeJS logging capabilities to catch issues before they impact your users. Start with Alerty today!

Related Reading