How to Use Grafana for Creating Dashboards and Monitoring

Grafana’s primary purpose is to visualize metrics and generate alerts. But what metrics? Metrics can be anything from request durations in an HTTP API server to the execution time of complex methods within your application.

In this tutorial, we’ll walk through adding metrics to a simple Node.js API server and visualizing the data using Grafana. We’ll use Prometheus to scrape the metrics from our API server.

Step 1: Install Grafana

We’ll start by running Grafana using Docker. Open your terminal and execute the following command:

```sh

docker run -d -p 3000:3000 --name=grafana grafana/grafana-oss

```

This command will pull the Grafana image and start a Grafana container on port 3000. You can access Grafana by navigating to `http://localhost:3000` in your browser. The default login credentials are:

- **Username:** admin

- **Password:** admin

Step 2: Create Your API Server in Node.js

After logging in, you can close the tab for now. We’ll come back to Grafana later.

Next, let’s set up a simple API server using Node.js and Express. Open your terminal and run the following commands:

```sh

mkdir api-server

cd api-server

npm init -y

npm install express

touch app.js

```

Now, let's set up a basic Express server. Open `app.js` and add the following code:

```js

const express = require("express");

const app = express();

const port = 4000;

app.get("/hello", (req, res) => {

  res.send({ msg: "hello" });

});

app.get("/hi", (req, res) => {

  res.send({ msg: "hi" });

});

app.listen(port, () => {

  console.log(`Example app listening on port ${port}`);

});

```

This code creates a simple API server with two endpoints: `/hello` and `/hi`.

Step 3: Add Metrics to Your API Server

To monitor the performance of your API server, we’ll use the `prom-client` library to collect metrics and expose them in a format that Prometheus can scrape.

Install the `prom-client` library:

```sh

npm install prom-client

```

Update `app.js` to include the metrics:

```js

const express = require("express");

const client = require("prom-client");

const app = express();

const port = 4000;

// Create a Registry to register the metrics

const register = new client.Registry();

// Create a Histogram metric

const httpRequestDurationMicroseconds = new client.Histogram({

  name: 'http_request_duration_seconds',

  help: 'Duration of HTTP requests in ms',

  labelNames: ['method', 'route', 'code']

});

// Register the histogram

register.registerMetric(httpRequestDurationMicroseconds);

// Register default metrics

client.collectDefaultMetrics({ register });

// Middleware to measure request durations

app.use((req, res, next) => {

  const end = httpRequestDurationMicroseconds.startTimer();

  res.on('finish', () => {

    end({ method: req.method, route: req.route.path, code: res.statusCode });

  });

  next();

});

app.get("/hello", (req, res) => {

  res.send({ msg: "hello" });

});

app.get("/hi", (req, res) => {

  res.send({ msg: "hi" });

});

// Expose metrics at /metrics endpoint

app.get('/metrics', async (req, res) => {

  res.set('Content-Type', register.contentType);

  res.end(await register.metrics());

});

app.listen(port, () => {

  console.log(`Example app listening on port ${port}`);

});

```


Looking for data visualization services?

Transform complex data into clear, actionable insights with our expert solutions! Ready to see your data in a whole new light?

Contact us today and start making data-driven decisions with confidence!

experience


    This code adds a histogram to measure the duration of HTTP requests and exposes the metrics at the `/metrics` endpoint.

    Step 4: Set Up Prometheus

    Now, we need Prometheus to scrape the metrics from our API server. Create a Prometheus configuration file named

    `prometheus.yml`:
    
    ```yaml
    
    global:
    
      scrape_interval: 15s
    
    scrape_configs:
    
      - job_name: 'nodejs_api_server'
    
        static_configs:
    
          - targets: ['host.docker.internal:4000']
    
    ```

    Download the Prometheus Docker image and run it with the configuration file:

    ```sh
    
    docker run -d -p 9090:9090 -v $(pwd)/prometheus.yml:/etc/prometheus/prometheus.yml prom/prometheus
    
    ```

    This command starts Prometheus on port 9090.

    Step 5: Visualize Metrics in Grafana

    1. Open Grafana at `http://localhost:3000` and log in.

    2. Add Prometheus as a data source:

       – Go to **Configuration** > **Data Sources**.

       – Click **Add data source** and select **Prometheus**.

       – Set the URL to `http://host.docker.internal:9090` and click **Save & Test**.

    3. Create a dashboard to visualize your metrics:

       – Go to **Create** > **Dashboard**.

       – Click **Add new panel**.

       – In the **Query** section, enter `http_request_duration_seconds_bucket`.

       – Customize the visualization as needed.

    Your Grafana dashboard should now display the metrics from your Node.js API server, allowing you to monitor request durations and other performance metrics.

    So thats it basically grafana needs a metric datasource, im using prometheus here but you can use anything even postgresql too, checkout their data sources to see the list of supported ones

    And from that we can transform our metrics into eye candy data