How to Set Up Prometheus for Monitoring a Node.js Application: A Step-by-Step Guide
Prometheus is a powerful open-source monitoring tool designed for reliability and scalability. It scrapes metrics from various services and provides a flexible query language for analysis. In this blog, we will set up Prometheus to monitor a Node.js application, configure it to scrape metrics, and verify that everything is working properly.
Prerequisites
- A Linux or macOS machine (Prometheus runs on many systems, but this guide uses Linux as an example).
- A basic understanding of Node.js and Express (or another Node.js framework).
- Node.js installed on your machine.
- Basic Docker knowledge (optional if running Prometheus in Docker).
Step 1: Install Prometheus
Option 1: Download and Install Prometheus (Manual)
- Go to the official Prometheus downloads page.
- Download the latest version of Prometheus:
wget https://github.com/prometheus/prometheus/releases/download/v2.46.0/prometheus-2.46.0.linux-amd64.tar.gz
3. Extract the tarball:
tar -xvzf prometheus-2.46.0.linux-amd64.tar.gz
4. Move into the extracted directory:
cd prometheus-2.46.0.linux-amd64
5. You’ll see binaries like prometheus
and promtool
in the directory. You can now run Prometheus by executing:
./prometheus
Prometheus will run on http://localhost:9090.
Option 2: Install Prometheus Using Docker (Recommended)
If you prefer to run Prometheus using Docker, use the following command:
docker run -d \
--name prometheus \
-p 9090:9090 \
-v /path/to/prometheus.yml:/etc/prometheus/prometheus.yml \
prom/prometheus
This command pulls the latest Prometheus image and runs it on port 9090. It also mounts your custom prometheus.yml
configuration file.
Step 2: Configure Prometheus
By default, Prometheus needs a configuration file named prometheus.yml
to know which services (targets) to scrape metrics from. You need to modify this file to include your Node.js application.
- Create or modify
prometheus.yml
to include your Node.js application as a target:
global:
scrape_interval: 15s # Set the default scrape interval to 15 seconds
scrape_configs:
- job_name: 'nodejs-app' # A unique name for your target
static_configs:
- targets: ['localhost:3000'] # Address where Node.js app metrics are exposed
2. Save the file and restart Prometheus:
./prometheus --config.file=prometheus.yml
Or if using Docker:
docker restart prometheus
Step 3: Set Up Node.js Application for Metrics
Prometheus collects metrics from a /metrics
endpoint on your application. To expose metrics from your Node.js app, you can use the prom-client
library.
1. Install prom-client
npm install prom-client
2. Integrate Prometheus Metrics in Node.js App
Here’s an example of how to integrate metrics collection into an Express.js app:
const express = require('express');
const client = require('prom-client');
const app = express();
const port = 3000;
// Create a Registry which registers 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']
});
// 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());
});
app.listen(port, () => {
console.log(`Node.js app listening on http://localhost:${port}`);
});
3. Run the Application
Run your Node.js app with the following command:
node app.js
The application will now expose metrics at http://localhost:3000/metrics
.
Step 4: Verify Prometheus Scraping
- Open the Prometheus UI at http://localhost:9090.
- Go to Status > Targets to check if Prometheus is successfully scraping the Node.js application.
If everything is set up correctly, you should see your nodejs-app
target listed with a "UP" status.
Step 5: Visualize Metrics
Once Prometheus starts scraping metrics from your Node.js app, you can use Prometheus’s query language (PromQL) to visualize these metrics.
- Go to the Graph section of the Prometheus UI.
- In the query input box, type the name of one of your metrics (e.g.,
http_requests_total
). - Click on Execute and switch to the Graph tab to see a visualization of the metric.
Prometheus provides a range of powerful functions in PromQL for advanced analysis of your metrics.
Conclusion
In this blog, we’ve successfully set up Prometheus to monitor a Node.js application. We:
- Installed Prometheus,
- Configured Prometheus to scrape metrics from a Node.js service,
- Integrated metrics collection in the Node.js application,
- Verified that metrics are being collected.
With Prometheus set up, you can now easily monitor and analyze your Node.js application’s performance metrics. You can also integrate it with Grafana for more advanced visualization and dashboards.