Monitoring PM2 with Prometheus and Grafana

If you’re managing applications with PM2 and want to monitor their performance, you can use PM2 Metrics with Prometheus and Grafana for detailed insights. This guide will walk you through the steps to set up PM2 Metrics, integrate it with Prometheus, and visualize the data with Grafana.

  1. Install PM2 Metrics

    Option A: Easy Install with PM2

You can quickly install PM2 Metrics using PM2's built-in installation method:

pm2 install pm2-metrics

Option B: Clone and Run as a Separate Application

Alternatively, you can clone the PM2 Prometheus Exporter repository and run it as a separate application:

git clone https://github.com/saikatharryc/pm2-prometheus-exporter.git
cd pm2-prometheus-exporter
npm install
pm2 start exporter.js --name pm2-metrics
  1. Access PM2 Metrics Once the exporter is running, you can view the metrics by opening your web browser and navigating to:
http://<HOST>:9209/metrics

Replace with the IP address or hostname of the machine where PM2 is running. By default, the metrics are served on port 9209.
if you can Access this URL and Allow port in firewall.

sudo ufw allow 9209
  1. Configure Prometheus To collect the PM2 metrics with Prometheus, you need to update your prometheus.yaml configuration file. Add the following block to the scrape_configs section:

     scrape_configs:
       - job_name: pm2-metrics
         scrape_interval: 10s
         scrape_timeout: 10s
         metrics_path: /metrics
         scheme: http
         static_configs:
           - targets:
             - localhost:9209
    

    Make sure to replace localhost with the actual address of your PM2 metrics endpoint if it’s running on a different host.

    1. Visualize Metrics with Grafana To visualize the metrics collected by Prometheus, you can use Grafana. Follow these steps:

Install Grafana: Download and install Grafana from the official website.

import dashboard of pm2, pm2 dashboard code 12745.

Add Prometheus Data Source:

Log in to Grafana. Go to Configuration > Data Sources. Click Add data source and select Prometheus. Configure the Prometheus data source by providing the URL (e.g., http://localhost:9090) and save the configuration. Create a Dashboard:

Go to Create > Dashboard. Click on Add new panel. Use Prometheus queries to create visualizations based on the metrics provided by PM2.
You can customize the panels to display various metrics related to your PM2-managed applications.

Conclusion

With PM2 Metrics, Prometheus, and Grafana, you can efficiently monitor your PM2 applications and visualize their performance. By following these steps, you’ll gain valuable insights into the health and efficiency of your applications, allowing you to make data-driven decisions and ensure optimal performance.