A Beginner’s Guide to PM2

5 min read
PM2

Introduction

PM2 is a process manager for Node.js applications that simplifies the process of managing and monitoring Node.js applications in production enviroment. In this beginner’s guide, we’ll learn what PM2 is, how to install it, and the key features that make it an essential tool for Node.js developers.

What is PM2?

PM2 is a process manager developed for managing applications running JavaScript. Although it was originally designed for Node.js applications, it is also often used in applications written in Python, Ruby, and other languages. The main purpose of PM2 is to provide the user with a tool to start, stop and manage applications in an orderly manner.

Key features of PM2 include:

  1. Process Management: PM2 allows you to manage and monitor Node.js processes efficiently. It can start, stop, and restart processes with ease, making it simple to deploy and update applications.
  2. Automatic Restart: PM2 can automatically restart your application in the event of a crash, ensuring that your application remains available even if unexpected issues occur.
  3. Load Balancing: PM2 provides built-in load balancing, allowing you to scale your application horizontally by running multiple instances and distributing the incoming traffic among them.
  4. Logging: PM2 collects and centralizes logs from your application, making it easier to troubleshoot issues and monitor the health of your application.
  5. Module Ecosystem: PM2 has a rich ecosystem of modules that can be added to extend its functionality. These modules cover various aspects, such as deployment, monitoring, and integration with other tools.

Installing PM2

Before you can start using PM2, you need to install it on your system. PM2 can be installed globally using npm, the Node.js package manager. Open your terminal or command prompt and run the following command:

npm install -g pm2

Once the installation is complete, you can verify that PM2 is installed by running:

pm2 --version

This should display the installed PM2 version, confirming a successful installation.

Basic Usage of PM2

Now that PM2 is installed, let’s explore some of the basic commands and features that will help you manage your Node.js applications effectively.

Starting an Application

To start a Node.js application with PM2, navigate to the directory containing your application’s main file (usually index.js or app.js) and run the following command:

pm2 start app.js

Replace app.js with the actual entry point file of your application. PM2 will start the application as a background process, and it will be assigned a process ID (PID).

Listing Running Processes

To view a list of all the processes managed by PM2, you can use the following command:

pm2 list

This will display information about each running process, including the process ID, name, status, and other details.

Restarting an Application

If you make changes to your application’s code and want to restart it, you can use the restart command:

pm2 restart app

Replace app with the name or process ID of your application.

Stopping an Application

To stop a running application, use the following command:

pm2 stop app

Replace app with the name or process ID of your application. This will gracefully stop the process.

Monitoring Application Logs

PM2 centralizes logs from your applications, making it easier to troubleshoot issues. You can view the logs for a specific application using the following command:

pm2 logs app

Replace app with the name or process ID of your application. This will display real-time logs, and you can press Ctrl + C to exit.

Deleting an Application

To remove an application from PM2, use the delete command:

pm2 delete app

Replace app with the name or process ID of your application. This will stop the process and remove it from PM2’s process list.

Advanced Features and Configuration

While the basic usage of PM2 can cover many use cases, there are advanced features and configuration options that can further enhance the management of your Node.js applications.

Configuration File

PM2 allows you to create a configuration file (ecosystem.config.js) for your applications. This file can include various settings, including environment variables, execution arguments, and more. Here’s a simple example:

// ecosystem.config.js
module.exports = {
  apps: [
    {
      name: "my-app",
      script: "app.js",
      instances: 2,
      exec_mode: "cluster",
      env: {
        NODE_ENV: "production",
        PORT: 3000,
      },
    },
  ],
};

In this example, we specify the application’s name, entry point script, the number of instances, execution mode, and environment variables.

Process Scaling

PM2 supports process scaling, allowing you to run multiple instances of your application to distribute incoming traffic. The instances option in the configuration file controls the number of instances. For example, setting instances: 4 will run four instances of your application.

Load Balancing

By default, PM2 uses a round-robin load-balancing algorithm to distribute incoming requests among running instances. This can be beneficial for improving the overall performance and reliability of your application.

Monitoring and Metrics

PM2 provides a built-in monitoring feature that allows you to visualize the resource usage and performance metrics of your running applications. You can access the monitoring dashboard using the following command:

pm2 monit

This dashboard provides information on CPU usage, memory consumption, and other metrics for each running process.

Startup Script Generation

PM2 can generate startup scripts to ensure that your applications are automatically started on system boot. To generate a startup script, use the following command:

pm2 startup

Follow the instructions provided by PM2 to configure the startup script based on your operating system.

Updating PM2

To keep PM2 up to date with the latest features and bug fixes, you can update it using npm:

npm install -g pm2@latest

This will install the latest version of PM2 globally on your system.

Conclusion

PM2 is a powerful and versatile tool used to manage Node.js applications in production environments. Features such as process management, automatic restart, load balancing and monitoring make it an important part of the Node.js development toolkit.

As you become more comfortable using PM2, you can explore its advanced features and configuration options to tailor it to the specific needs of your projects. Whether you’re a solo developer or part of a team, PM2 can significantly streamline your workflow and contribute to the overall stability and performance of your Node js applications.

If you want to read more, check the following articles:

Thank you for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *