Blog

Streamline your Node.JS by monitoring with PM2: A Beginner’s Guide

ByRahul Mahawar
August 1st . 8 min read
Streamline your Node.JS by monitoring with PM2

As a developer, you know the pain of application downtime all too well. A single critical error can bring your carefully crafted APIs to a grinding halt, frustrating users and causing sleepless nights for your team.

That’s where PM2 comes in — a robust process manager that acts as a guardian angel for your Node.js applications.

In this beginner’s guide, you’ll gain the power to monitor your applications in real time, receive instant notifications when errors occur, and quickly identify and resolve issues before they escalate.

Say goodbye to the days of manually restarting crashed processes or scouring through logs to pinpoint the root cause of a problem.

So get ready to streamline your Node.js monitoring experience and take control of your application’s health with PM2!

What is PM2?

PM2 is a powerful process manager for Node.js applications that simplifies running and managing Node.js processes in production environments. It acts as a daemon process manager that keeps Node.js applications alive forever, automatically restarting them if they crash or the server is restarted. PM2 provides a comprehensive set of features including load balancing across multiple instances, clustering for improved performance, monitoring and logging capabilities, terminal access for debugging, and seamless deployment with zero downtime.

By handling process management, monitoring, and clustering out-of-the-box, PM2 allows developers to focus on writing code while ensuring their Node.js applications run reliably and efficiently in production.

Overview of PM2 Monitoring Tool

PM2 offers a built-in monitoring tool that simplifies the process of monitoring the resource usage of your Node.js applications. With PM2, you can easily monitor memory and CPU utilization straight from your terminal, giving you a simple way to track the performance and resource utilization of the Node.js processes it manages. The monitoring tool provides detailed metrics and insights into critical aspects like CPU usage, memory consumption, event loop delays, and more.

This is where PM2 monitoring comes into play. With PM2, you can monitor the health and performance of your Node.js application in real time, even in a production environment.

Here’s how PM2 monitoring can help in this scenario:

  • Resource Monitoring: PM2 monitors critical system resources like CPU usage, memory consumption, event loop delays, and more for each running Node.js process. This data helps identify potential bottlenecks or performance issues.
  • Log Monitoring: PM2 consolidates logs from all running processes into a centralized location, allowing you to view and search through these logs for troubleshooting and debugging purposes.
  • Monitoring Dashboard: PM2 provides a monitoring dashboard, accessible via the command line or a web interface, which displays real-time metrics and information about the running processes.
  • Metrics Visualization: The monitoring dashboard visualizes various metrics, such as CPU and memory usage over time, making it easier to identify trends and potential issues.

PM2 monit vs PM2 logs

  • PM2 monit: PM2 monit is the built-in monitoring tool that provides an ad-hoc, real-time view of your running Node.js processes managed by PM2. It displays various metrics and resource usage data, including CPU, memory, event loop delays, and logs in real time.
  • PM2 logs: On the other hand, PM2 logs offer a retrospective view through saved logs from all running processes, although it also supports real-time log streaming. It consolidates logs from all processes into a centralized location, enabling easier log management, searching, and debugging.

Differences and Use Cases

While both PM2 monit and PM2 logs are useful tools, they serve different purposes:

  • PM2 monit is primarily used for monitoring resource usage, performance metrics, and general process management. It provides a comprehensive view of your application's health and performance.
  • PM2 logs are focused on log management and debugging. It allows you to easily view and search through logs from all processes, which is crucial for troubleshooting and identifying issues.

Installing PM2 and setup with Node.js Application

PM2 can be installed globally using npm (Node.js package manager). Open your terminal and run the following command:

# npm install pm2 -g

This will install PM2 globally on your system, allowing you to use it from anywhere.

Configuring Node.js Application

Once PM2 is installed, you need to configure your Node.js application for PM2 to manage it. Here are the typical steps:

  • Navigate to your application directory
# cd /path/to/your/app

  • Start your application with PM2
# pm2 start index.js

Replace index.js with the entry point file of your Node.js application.

Generate startup script (optional but recommended) PM2 can generate a startup script that will automatically restart your application if the server reboots.

Run the following command

# pm2 startup

This will provide instructions to set up the startup script for your specific system (e.g., systemd, upstart, etc.). Follow the provided instructions. Save the current process list To save the current list of running processes managed by PM2, run

# pm2 save

This will save the process list, allowing PM2 to automatically restore and restart your application after a server reboot.

Monitoring and Managing with PM2

Once your Node.js application is running under PM2, you can use various PM2 commands to monitor and manage it:

  • pm2 list: View all the Node.js applications and processes currently being managed by PM2.
  • pm2 logs: View consolidated logs from all running processes.
  • pm2 flush app: Clear the logs for a specific process or application.
  • pm2 restart app: Restart a specific process or application.
  • pm2 stop app: Stop a specific process or application.
  • pm2 delete app: Remove a process or application from PM2's management.

Access and Utilize the PM2 Web Dashboard

To implementing a robust dashboard monitoring system for PM2 allowed us to track real-time performance metrics and ensure proactive management of our processes. The PM2 Web Dashboard gives you a user-friendly interface to monitor and manage your Node.js applications.

Build secure, upgradable and stand-alone application here

Here’s how to access it

# pm2 monit

To access the PM2 dashboard, visit https://app.pm2.io and sign up as demonstrated in the screenshot below.

PM1.jpg

  • After successfully logging in, create a bucket to group your Node.js applications/servers. Here is an existing bucket named “revbits” with 1 team member to access.

PM2.jpg

PM3.jpg

  • To link or connect the server, copy the pm2 link command and run it into the application server
# pm2 link 7x5om9uy72q1k7t d6kxk8ode2cn6q9

Refresh the PM2 dashboard page now. You should see that your server is connected and show a list of all your Node.js applications with all the details.

PM4.jpg

Monitoring Node.js Applications with PM2 Web Dashboard

Effective monitoring is a crucial aspect of maintaining robust and reliable Node.js applications. PM2 provides a powerful, user-friendly web dashboard that offers real-time insights into your application’s performance.

Let’s explore the key features and metrics available on the PM2 Web Dashboard using the following example:

Key Features and Metrics

General Overview:

  • Application Name: Displays the name of the application being monitored, in this case, revbits-homepage-new-d514.
  • Process Count: Indicates the number of processes running, shown as 4 processes.
  • Status: Shows the status of the processes, such as online for 3 days.

Resource Utilization:

  • CPU Usage: The dashboard shows the current CPU usage, which is 1% in this example, indicating minimal CPU load.
  • Memory Usage: Displays the memory usage of the application, 117MiB here.

Performance Metrics:

  • Event Loop Latency: Critical for understanding the responsiveness of your application. Here, it is 0.5ms, which is within an optimal range.
  • HTTP and HTTPS Latency: Measures the average latency for HTTP and HTTPS requests. The example shows 0ms for HTTP and 2ms for HTTPS.
  • Heap Usage: Indicates the memory heap usage. The Used Heap Size is 38MiB, and the overall Heap Usage is 86%.

Additional Insights:

  • Active Handles and Requests: Shows the number of active handles (10.8) and active requests (0) being processed.
  • Event Loop Latency p95: This metric provides the 95th percentile of event loop latency, here shown as 1.2ms.
  • HTTP and HTTPS P95 Latency: Indicates the 95th percentile latency for HTTP (1ms) and HTTPS (177ms) requests.

Management and Versioning:

  • Restarts and Issues: The dashboard shows the number of restarts (73588) and any issues (0 in this case).
  • Version Information: Displays the current version of the application and relevant branch information (#master - 416fa26ed782).

Controls and Actions:

  • Restart Apps: Allows for quick restarting of applications.
  • Show Logs: Provides access to application logs for troubleshooting.
  • Reset Monit: Resets the monitoring statistics.

PM5.jpg PM6.jpg

If you want to disconnect your PM2 instance from the PM2 dashboard, you can directly execute the following command

# pm2 unlink

Conclusion

PM2 streamlines the management and monitoring of your Node.js applications, ensuring they run smoothly and efficiently. To ensure the seamless running of your application, use PM2 in Node.js to manage and monitor your processes.

With real-time alerts, comprehensive dashboards, and robust monitoring tools, PM2 allows you to quickly address issues and maintain control over your application’s health.

By integrating PM2, you can focus more on development and less on manual process management, enhancing both productivity and reliability.

Share:
0
+0