Navigate the PM2 Process Manager: A Simplified Guide for Beginners

If you’re a Node.js developer, you know the importance of process management for ensuring the smooth operation of your applications. As your application grows and more users start interacting with it, managing the various processes becomes crucial. This is where a process manager like PM2 comes in handy. PM2, or Process Manager 2, is a versatile production process manager written in Node.js. It offers a complete feature set and is widely used by developers and enterprises alike.

In this comprehensive guide, we will walk you through the various aspects of using PM2 for process management in your Node.js applications. We’ll explore the key features of PM2, installation instructions, starting applications in different modes, monitoring running applications, restarting processes, clustering, log management, and much more. By the end of this guide, you’ll have a clear understanding of how to effectively use PM2 to enhance the performance and reliability of your Node.js applications.

Key Takeaways

  • PM2 is a powerful process manager for Node.js applications that helps ensure application uptime and performance.
  • PM2 provides various features like process monitoring, restarting, clustering, log management, and more.
  • You can install PM2 globally using npm and check the version to ensure it’s properly installed.
  • PM2 can be used to start Node.js applications in both development and production modes.
  • Monitoring running applications and restarting processes can be easily done using PM2’s intuitive commands.
  • Clustering allows you to scale your application by utilizing multiple processes.
  • PM2 provides robust log management capabilities, including log rotation.
  • It’s recommended to explore PM2’s documentation for more advanced features and capabilities.

Why Do You Need a Process Manager?

Before diving into the details of PM2, let’s understand why process management is crucial for Node.js applications. When you have a Node.js application in production, it typically consists of multiple processes running simultaneously to handle incoming requests. These processes can be individual instances of your application, each capable of handling a certain number of requests at a time.

Managing these processes manually can become a tedious task, especially when you have to monitor their performance, restart them when they crash, and scale them as the user load varies. This is where a process manager like PM2 becomes invaluable.

PM2 takes care of all these aspects and provides a unified interface for managing your Node.js processes. It simplifies tasks like starting, monitoring, and restarting processes, allowing you to focus on developing your application without worrying about the underlying infrastructure.

Installing PM2 and Checking the Version

To get started with PM2, you first need to install it globally on your system. PM2 can be installed using npm, the package manager for Node.js. Open your terminal and run the following command:

npm install pm2@latest -g

Once the installation is complete, you can verify that PM2 has been installed correctly by checking its version. Run the following command:

pm2 --version

This will display the version of PM2 installed on your system. Make sure you have the latest version to enjoy all the latest features and bug fixes.

Starting Node.js Applications in Development Mode with PM2

PM2 provides different modes for starting Node.js applications, depending on the environment you’re working in. Let’s start with the development mode.

To start a Node.js application in development mode using PM2, navigate to the root directory of your application using the terminal. Once in the application’s root directory, run the following command:

pm2 start app.js --name="my-app" --watch

In this command, app.js is the main file of your Node.js application. Replace it with the actual filename if yours is different. The --name flag allows you to give a custom name to your application. In this example, we’ve given it the name “my-app”. The --watch flag enables the watch mode, which means PM2 will restart the application whenever any file changes are detected.

Once you run this command, PM2 will start your application and provide you with a unique process ID (PID) assigned to it. You can use this PID to reference and manage the application later on.

Starting Node.js Applications in Production Mode with PM2

In addition to the development mode, PM2 also allows you to start Node.js applications in production mode. Running your application in production mode usually involves additional optimizations and configurations to ensure better performance and stability.

To start a Node.js application in production mode using PM2, navigate to the root directory of your application using the terminal, just like before. Once in the application’s root directory, run the following command:

pm2 start app.js --name="my-app" --env production

Here, app.js is the main file of your Node.js application, and you can replace it with the actual filename if yours is different. The --name flag allows you to specify a custom name for your application, and the --env flag sets the environment to “production”.

When you start your application in production mode, PM2 applies additional optimizations and configurations to ensure the best performance. It utilizes Node.js clustering to distribute the load across multiple instances of your application, making it more robust and scalable.

Monitoring Running Applications in PM2

Once you’ve started your applications with PM2, you can easily monitor their status and performance using PM2’s monitoring commands. These commands provide valuable information about the running processes, including CPU and memory usage, uptime, and other metrics.

To check the list of all running applications, run the following command:

pm2 list

This command will display a table showing all the applications managed by PM2, along with their status, CPU and memory usage, and other details.

If you want more detailed information about a specific application, you can use the pm2 show command followed by the application’s name or process ID. For example:

pm2 show my-app

This command will show detailed information about the application with the specified name or process ID.

In addition to displaying information about individual processes, PM2 provides a terminal-based dashboard called PM2 Monit. This dashboard offers a real-time view of your application’s resource usage, including CPU, memory, and disk usage.

To start the PM2 Monit dashboard, run the following command in your terminal:

pm2 monit

This will open the dashboard in your terminal, allowing you to monitor your running applications at a glance.

Monitoring your applications with PM2 gives you valuable insights into their performance and resource utilization. It enables you to identify any potential bottlenecks or issues and take appropriate actions to optimize your application’s performance.

Restarting Node.js Applications with PM2

One of the key benefits of using a process manager like PM2 is the ability to easily restart your Node.js applications whenever needed. PM2 provides several commands to restart processes in different scenarios, ensuring minimal downtime and maximum availability.

To restart a specific application managed by PM2, use the following command:

pm2 restart my-app

Here, “my-app” refers to the name given to your application when it was started using PM2. Replace it with the actual name of your application.

If you don’t remember the application’s name, you can use the pm2 list command to get a list of all running applications and their respective names.

In addition to restarting individual applications, PM2 also provides a command to restart all running applications at once. To restart all applications, run the following command:

pm2 restart all

This will restart all applications managed by PM2, ensuring they are up and running with the latest changes and configurations.

Configuring Auto Restart Based on Memory Usage, Cron Schedule, File Changes, and Delay

PM2 allows you to configure automatic restarts for your applications based on various conditions. This is particularly useful when you want to ensure your application remains responsive and available even in exceptional circumstances.

You can configure PM2 to automatically restart an application when its memory usage exceeds a certain threshold. To set up memory-based auto restart, use the following command:

pm2 set my-app max_memory_restart 100M

In this example, “my-app” refers to the name of the application for which you want to configure the auto restart based on memory usage. Replace it with the actual name of your application. The max_memory_restart option specifies the maximum amount of memory, including units like M (megabytes) or G (gigabytes). If the application’s memory usage exceeds this threshold, PM2 will automatically restart it.

Another way to configure auto restarts is based on a cron schedule. A cron schedule allows you to define a recurring pattern for when the application should be restarted. For example, to restart an application every day at 3 AM, use the following command:

pm2 set my-app cron "* 3 * * *"

Replace “my-app” with the name of your application, and “ 3 ” with your desired cron schedule.

PM2 also allows you to configure auto restarts when specific files change. This is useful during development when you want your application to automatically reflect the changes you make to the source code.

To configure file-based auto restart, use the following command:

pm2 set my-app watch true

This command enables the watch mode for the specified application, so it restarts whenever any file changes are detected in the application’s directory.

Finally, PM2 allows you to add a delay before restarting an application. This can be useful in scenarios where you want to ensure the application has enough time to clean up resources or complete any ongoing operations before being restarted.

To configure a delay before restarting, use the following command:

pm2 set my-app restart_delay 5000

In this example, “my-app” refers to the name of your application, and “5000” specifies the delay in milliseconds. PM2 will wait for this duration before restarting the application.

Ignoring Certain Exit Codes When Auto Restarting with PM2

When an application exits unexpectedly, it usually returns an exit code to indicate the reason for the exit. By default, PM2 automatically restarts an application when it exits with an exit code other than 0. However, there may be cases where you want to ignore certain exit codes and prevent automatic restarts.

To configure PM2 to ignore specific exit codes, use the following command:

pm2 set my-app ignore_watch "1 2"

Here, “my-app” refers to the name of your application, and “1 2” specifies the exit codes to ignore. In this example, PM2 will not automatically restart the application if it exits with an exit code of 1 or 2.

You can specify multiple exit codes by separating them with spaces.

Restarting Processes After a System Reboot Using PM2’s Startup Feature

To ensure your Node.js application starts automatically after a system reboot, PM2 provides a startup feature. This feature configures your application to be automatically started by the operating system during the boot process.

To enable PM2’s startup feature, run the following command:

pm2 startup

This command will generate a command that you need to run as a privileged user (e.g., using sudo). Copy the generated command from the output of this command and run it in your terminal.

Once the startup script is installed, PM2 will automatically start your previously managed applications whenever the system reboots.

Clustering in Node.js Applications Using PM2

Node.js clustering allows you to scale your application by utilizing multiple processes to handle incoming requests. PM2 makes clustering easy by providing built-in support for Node.js clustering.

To enable clustering in your Node.js application using PM2, run the following command:

pm2 start app.js --name="my-app" -i max

Here, app.js refers to the main file of your Node.js application, and “my-app” is the desired name for your application. The -i flag is used to specify the number of instances (or workers) to create for your application. By using the value “max”, PM2 will create as many instances as there are CPU cores on your system.

Clustering helps distribute the incoming requests across multiple instances, improving the overall performance and scalability of your application.

Log Management in PM2

Managing logs is an essential part of maintaining and troubleshooting applications. PM2 provides robust log management capabilities, making it easier to collect, analyze, and manage logs generated by your Node.js applications.

When you start an application using PM2, it automatically captures and stores the application’s output in log files. By default, PM2 creates a log file for each application, named app-name-out.log and app-name-error.log, where “app-name” refers to the name of your application.

You can view the logs of a particular application by running the following command:

pm2 logs my-app

In this command, “my-app” is the name of the application whose logs you want to view.

To manage the size of log files and prevent them from growing indefinitely, PM2 provides a built-in log rotation feature. By default, PM2 rotates logs based on file size, keeping the log files within a certain size limit.

PM2 also allows you to customize the log rotation behavior according to your requirements by modifying the configuration file. The configuration options include log file size, the number of log files to keep, and the rotation interval.

Conclusion

PM2 is a powerful process manager for Node.js applications that simplifies the management and monitoring of your application’s processes. In this guide, we’ve covered the key aspects of using PM2, including installation, starting applications in different modes, monitoring running applications, restarting processes, clustering, and log management.

By implementing PM2 in your Node.js projects, you can ensure better application performance, increased uptime, and streamlined process management. The features provided by PM2, such as auto restarts, log management, and clustering, greatly simplify the task of managing your Node.js applications in production.

However, this is just the tip of the iceberg. PM2 offers many more advanced features and capabilities that can further enhance your experience with process management. It’s recommended to explore PM2’s official documentation for more in-depth information on these features.

So, go ahead and give PM2 a try in your Node.js projects. It’s a robust and versatile tool that will undoubtedly improve the reliability and performance of your applications.

Find more about PM2’s documentation on their website.