Table of Contents
Introduction
Prometheus is an open-source monitoring and alerting toolkit designed for reliability and scalability. It is especially well-suited for monitoring dynamic systems like microservices and applications built with Node.js. This documentation provides a step-by-step guide to setting up Prometheus for monitoring a Node.js application using the prom-client
library to expose application metrics.
Prerequisites
Before starting the installation, ensure you have the following prerequisites in place:
Operating System: A Linux or macOS machine.
Node.js: A basic understanding of Node.js and Express (or another Node.js framework).
Node.js Installed: Confirm Node.js is installed by running:
node -v
Docker (Optional): Basic understanding of Docker if you prefer to run Prometheus in a container.
Installation Steps
Option 1: Manual Installation
Download Prometheus: Fetch the latest version of Prometheus:
wget https://github.com/prometheus/prometheus/releases/download/v2.46.0/prometheus-2.46.0.linux-amd64.tar.gz
Extract the Tarball: Unpack the downloaded file:
tar -xvzf prometheus-2.46.0.linux-amd64.tar.gz
Navigate to the Directory: Change to the extracted Prometheus directory:
cd prometheus-2.46.0.linux-amd64
Start Prometheus: Launch Prometheus with the default configuration:
./prometheus
Prometheus will be accessible at
http://localhost:9090
.
Option 2: Docker Installation
If you prefer using Docker, follow these steps:
Run Prometheus in a Docker Container: Ensure to replace
/path/to/prometheus.yml
with the actual path to your Prometheus configuration file:docker run -d \ --name prometheus \ -p 9090:9090 \ -v /path/to/prometheus.yml:/etc/prometheus/prometheus.yml \ prom/prometheus
Configuring Prometheus
Prometheus requires a configuration file named prometheus.yml
to define the services from which it should scrape metrics.
Create or Modify the
prometheus.yml
Configuration: Below is a sample configuration file that defines scraping for your Node.js application:global: scrape_interval: 15s # Default scrape interval scrape_configs: - job_name: 'nodejs-app' # Unique job name for the application static_configs: - targets: ['localhost:3000'] # Address of the Node.js application metrics endpoint
Save the Configuration and Restart Prometheus:
If running Prometheus manually:
./prometheus --config.file=prometheus.yml
If using Docker:
docker restart prometheus
Setting Up the Node.js Application for Metrics
Prometheus collects metrics from a /metrics
endpoint on your application. The prom-client
library is used to expose these metrics.
Install the
prom-client
Library: In your Node.js project directory, install the library:npm install prom-client
Integrate Prometheus Metrics into Your Node.js Application: Below is an example of an Express.js application that exposes metrics:
const express = require('express'); const client = require('prom-client'); const app = express(); const port = 3000; // Create a Registry to register the metrics const register = new client.Registry(); // Add default metrics to the registry client.collectDefaultMetrics({ register }); // Custom metric - Counter const requestCounter = new client.Counter({ name: 'http_requests_total', help: 'Total number of HTTP requests', labelNames: ['method', 'endpoint'] }); // Middleware to increment the counter on each request app.use((req, res, next) => { requestCounter.inc({ method: req.method, endpoint: req.url }); next(); }); // Expose /metrics endpoint for Prometheus app.get('/metrics', async (req, res) => { res.set('Content-Type', register.contentType); res.end(await register.metrics()); }); // Start the application app.listen(port, () => { console.log(`Node.js app listening on http://localhost:${port}`); });
Run Your Node.js Application: Launch your application using:
node app.js
The application will now expose metrics at
http://localhost:3000/metrics
.
Verifying Prometheus Scraping
Access the Prometheus UI: Open your web browser and navigate to
http://localhost:9090
.Check Scrape Targets: Go to Status > Targets to confirm that Prometheus is successfully scraping the Node.js application. Your
nodejs-app
target should be listed with a "UP" status.
Visualizing Metrics
Once Prometheus begins scraping metrics, you can use its powerful query language, PromQL, to visualize these metrics.
Navigate to the Graph Section of the Prometheus UI.
Enter Your Metric Query: In the query input box, type the name of a metric (e.g.,
http_requests_total
).Execute the Query and switch to the Graph tab to visualize the metric.
Conclusion
In this guide, we successfully set up Prometheus to monitor a Node.js application. We have:
Installed Prometheus,
Configured it to scrape metrics from a Node.js service,
Integrated metrics collection within the Node.js application,
Verified that metrics are being collected.
With Prometheus now configured, you can effectively monitor and analyze your Node.js application’s performance metrics. For enhanced visualization and dashboard capabilities, consider integrating Prometheus with Grafana.