> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Demo Deploying Prometheus and Grafana in Kubernetes

> Step by step lab for deploying Prometheus and Grafana in Kubernetes, inspecting Prometheus configuration, adding Grafana data source, and visualizing metrics.

Welcome to the second lab in this course. This step-by-step guide shows how to deploy Prometheus and Grafana inside a Kubernetes cluster, inspect Prometheus configuration and metrics, and connect Prometheus as a data source in Grafana. This lesson uses plain Kubernetes manifests so you can inspect the exact configuration files Prometheus and Grafana rely on; in production you would typically use the Prometheus Operator or Helm charts.

In a production environment you would typically deploy Prometheus via the Prometheus Operator or Helm charts. This lesson uses basic manifests so you can see the configuration files Prometheus and Grafana rely on.

Contents

* Create a dedicated monitoring namespace
* Inspect Prometheus configuration and create a ConfigMap
* Deploy Prometheus (Deployment + Service + RBAC)
* Explore Prometheus targets and key metrics
* Deploy Grafana and add Prometheus as a data source
* Visualize Prometheus metrics in Grafana

## 1) Create a monitoring namespace

Create a separate namespace to keep monitoring resources (Prometheus, Grafana) isolated from application and control-plane objects.

Verify existing namespaces:

```bash theme={null}
kubectl get ns
```

Example output:

```console theme={null}
NAME              STATUS    AGE
default           Active    3m9s
kube-flannel      Active    3m5s
kube-node-lease   Active    3m9s
kube-public       Active    3m9s
kube-system       Active    3m9s
```

Create the `monitoring` namespace:

```bash theme={null}
kubectl create namespace monitoring
```

Confirm the namespace exists:

```bash theme={null}
kubectl get ns
```

Example output:

```console theme={null}
NAME              STATUS   AGE
default           Active   4m39s
kube-flannel      Active   4m35s
kube-node-lease   Active   4m39s
kube-public       Active   4m39s
kube-system       Active   4m39s
monitoring        Active   3s
```

## 2) Inspect Prometheus manifests

List the Prometheus manifest directory to see what files are available:

```bash theme={null}
ls prometheus/
```

Example output:

```console theme={null}
prometheus-deployment.yaml  prometheus-nodeport.yaml  prometheus.yml
```

Table: Prometheus files and purpose

| File | Purpose |
| - | - |
| `prometheus.yml` | Prometheus server global settings and `scrape_configs` |
| `prometheus-deployment.yaml` | Deployment, Service (ClusterIP), RBAC, and volumes for Prometheus |
| `prometheus-nodeport.yaml` | Alternative Service manifest exposing Prometheus via NodePort (optional) |

Open `prometheus.yml` to inspect global settings (scrape/evaluation intervals) and `scrape_configs` (jobs and discovery). Example:

```yaml theme={null}
global:
  scrape_interval: 15s
  evaluation_interval: 15s

scrape_configs:
  - job_name: "prometheus"
    static_configs:
      - targets: ["localhost:9090"]

  - job_name: "kubernetes-nodes"
    kubernetes_sd_configs:
      - role: node
    relabel_configs:
      - source_labels: [__address__]
        regex: "(.*):10250"
        replacement: "$1:9100"
        target_label: __address__
```

Question (lab): What are the job names under `scrape_configs`?
Answer: `prometheus` and `kubernetes-nodes`.

### Create a ConfigMap from `prometheus.yml`

Create a ConfigMap named `prometheus-config` in the `monitoring` namespace from the file:

```bash theme={null}
kubectl create configmap prometheus-config -n monitoring --from-file=prometheus.yml=prometheus/prometheus.yml
```

Verify the ConfigMap exists:

```bash theme={null}
kubectl get configmap -n monitoring
```

Example output:

```console theme={null}
NAME                 DATA   AGE
kube-root-ca.crt     1      3m55s
prometheus-config    1      6s
```

View the ConfigMap contents:

```bash theme={null}
kubectl get configmap prometheus-config -n monitoring -o yaml
```

Example output (truncated):

```yaml theme={null}
apiVersion: v1
data:
  prometheus.yml: |-
    global:
      scrape_interval: 15s
      evaluation_interval: 15s
    scrape_configs:
      - job_name: "prometheus"
        static_configs:
          - targets: ["localhost:9090"]
      - job_name: "kubernetes-nodes"
        kubernetes_sd_configs:
          - role: node
        relabel_configs:
          - source_labels: [__address__]
            regex: "(.*):10250"
            replacement: "$1:9100"
            target_label: __address__
kind: ConfigMap
metadata:
  name: prometheus-config
  namespace: monitoring
```

## 3) Deploy Prometheus

Inspect `prometheus-deployment.yaml` — it contains:

* Deployment running the Prometheus container (args point to the config file and storage path)
* A `ConfigMap` volume mounted at `/etc/prometheus`
* A ClusterIP Service exposing Prometheus internally at port 9090
* ServiceAccount, ClusterRole, and ClusterRoleBinding for Kubernetes discovery

Important container snippet from `prometheus-deployment.yaml`:

```yaml theme={null}
apiVersion: apps/v1
kind: Deployment
metadata:
  name: prometheus
  namespace: monitoring
spec:
  replicas: 1
  selector:
    matchLabels:
      app: prometheus
  template:
    metadata:
      labels:
        app: prometheus
    spec:
      serviceAccountName: prometheus
      containers:
      - name: prometheus
        image: prom/prometheus:v2.38.0
        args:
        - '--config.file=/etc/prometheus/prometheus.yml'
        - '--storage.tsdb.path=/prometheus'
        - '--web.console.libraries=/usr/share/prometheus/console_libraries'
        - '--web.console.templates=/usr/share/prometheus/consoles'
        ports:
        - containerPort: 9090
        volumeMounts:
        - name: prometheus-config
          mountPath: /etc/prometheus
        - name: prometheus-storage
          mountPath: /prometheus
  volumes:
  - name: prometheus-config
    configMap:
      name: prometheus-config
  - name: prometheus-storage
    emptyDir: {}
```

Apply the Prometheus manifest:

```bash theme={null}
kubectl apply -f prometheus/prometheus-deployment.yaml
```

Example apply output:

```console theme={null}
deployment.apps/prometheus created
service/prometheus created
serviceaccount/prometheus created
clusterrole.rbac.authorization.k8s.io/prometheus created
clusterrolebinding.rbac.authorization.k8s.io/prometheus created
```

Watch the Prometheus pod start:

```bash theme={null}
kubectl get pods -n monitoring -w
```

Example pod output:

```console theme={null}
NAME                         READY   STATUS    RESTARTS   AGE
prometheus-77d86fcd8c-qrq6q  1/1     Running   0          10s
```

## 4) Inspect Prometheus targets and metrics

Open the Prometheus UI (port-forward or NodePort) and go to Status → Targets. This page shows endpoints Prometheus is scraping based on `scrape_configs` from the loaded ConfigMap.

Typical Targets examples:

* Prometheus scrape target:

Endpoint:
[http://localhost:9090/metrics](http://localhost:9090/metrics)

Labels:
`instance="localhost:9090" job="prometheus"`

* Node exporter (kubernetes-nodes) target (example error):

Endpoint:
[http://192.168.228.25:9100/metrics](http://192.168.228.25:9100/metrics)

Labels:
`instance="controlplane" job="kubernetes-nodes"`

Error:
Get "[http://192.168.228.25:9100/metrics](http://192.168.228.25:9100/metrics)": dial tcp 192.168.228.25:9100: connect: connection refused

Prometheus also exposes builtin metrics. The `up` metric is the simplest health indicator:

* `up` = 1 → target scraped successfully
* `up` = 0 → target unreachable / scrape failed

Example (Prometheus expression `up`):

```text theme={null}
up{instance="localhost:9090", job="prometheus"} 1
up{instance="controlplane", job="kubernetes-nodes"} 0
```

Another useful internal metric is `prometheus_http_requests_total` (HTTP handler request totals), helpful for inspecting Prometheus' own behavior:

Example series:

```text theme={null}
prometheus_http_requests_total{code="200", handler="/", instance="localhost:9090", job="prometheus"}
prometheus_http_requests_total{code="200", handler="/-/healthy", instance="localhost:9090", job="prometheus"}
prometheus_http_requests_total{code="200", handler="/api/v1/*path", instance="localhost:9090", job="prometheus"}
```

These counters accumulate over the lifetime of the Prometheus process.

## 5) Deploy Grafana

Inspect `grafana/grafana-deployment.yaml`. The Deployment runs Grafana on port 3000; for this lesson the admin password is set by environment variables (lab/demo purpose only).

Key parts of the Grafana manifest:

```yaml theme={null}
apiVersion: apps/v1
kind: Deployment
metadata:
  name: grafana
  namespace: monitoring
spec:
  replicas: 1
  selector:
    matchLabels:
      app: grafana
  template:
    metadata:
      labels:
        app: grafana
    spec:
      containers:
      - name: grafana
        image: grafana/grafana:10.2.2
        ports:
        - containerPort: 3000
        env:
        - name: GF_SECURITY_ADMIN_PASSWORD
          value: "admin"
        - name: GF_USERS_ALLOW_SIGN_UP
          value: "false"
        volumeMounts:
        - name: grafana-storage
          mountPath: /var/lib/grafana
  volumes:
  - name: grafana-storage
    emptyDir: {}

---
apiVersion: v1
kind: Service
metadata:
  name: grafana
  namespace: monitoring
spec:
  type: ClusterIP
  ports:
  - port: 3000
    targetPort: 3000
  selector:
    app: grafana
```

Apply Grafana:

```bash theme={null}
kubectl apply -n monitoring -f grafana/grafana-deployment.yaml
```

Verify pods:

```bash theme={null}
kubectl get pods -n monitoring
```

Example output:

```console theme={null}
NAME                                READY   STATUS    RESTARTS   AGE
grafana-6ccf684dcf-9vrf9            1/1     Running   0          7s
prometheus-77d86fcd8c-qrq6q         1/1     Running   0          8m2s
```

Grafana login for this lesson:

* Username: `admin`
* Password: `admin`

For lab/demo purposes the admin password is set via an environment variable and uses the default `admin` password. Do NOT use default or insecure credentials in production — rotate credentials and use secure secrets management.

You may get a browser warning about insecure default credentials — this is expected in the lab environment.

## 6) Add Prometheus as a Grafana data source

Open Grafana and navigate to Connections → Data sources → Add data source.

![A browser screenshot of Grafana's "Add data source" page showing a list of time-series database options, including Prometheus, Graphite, InfluxDB, and OpenTSDB. The sidebar shows the Connections → Data sources menu.](https://mintcdn.com/kodekloud-c4ac6d9a/qM9vA-hQoWNCxcKa/images/Grafana-Prometheus-for-Metrics-Driven-Observability/Prometheus-and-Grafana-Introduction/Demo-Deploying-Prometheus-and-Grafana-in-Kubernetes/grafana-add-data-source-timeseries-options.jpg?fit=max\&auto=format\&n=qM9vA-hQoWNCxcKa\&q=85\&s=019d49c1cfb421597fbb7c3ca4eac4a5)

Choose Prometheus as the data source. Use the in-cluster Service DNS name so Grafana (running in a separate pod) can reliably reach Prometheus:

```text theme={null}
http://prometheus.monitoring.svc.cluster.local:9090
```

No authentication is required for this lab. Click **Save & Test** — Grafana should report that it successfully queried the Prometheus API.

![A dark-themed Grafana browser screenshot showing the Prometheus data source settings page with options like custom query parameters and HTTP method set to POST. A green banner reports "Successfully queried the Prometheus API" and there are "Delete" and "Save & Test" buttons at the bottom.](https://mintcdn.com/kodekloud-c4ac6d9a/qM9vA-hQoWNCxcKa/images/Grafana-Prometheus-for-Metrics-Driven-Observability/Prometheus-and-Grafana-Introduction/Demo-Deploying-Prometheus-and-Grafana-in-Kubernetes/grafana-prometheus-datasource-post-success.jpg?fit=max\&auto=format\&n=qM9vA-hQoWNCxcKa\&q=85\&s=9ebd5987b5f9497bc75b007f17f723b5)

Why use the Service DNS instead of `localhost`?

* Grafana and Prometheus run in different pods; `localhost` within the Grafana pod would point to Grafana itself. Use the Kubernetes Service DNS (`prometheus.monitoring.svc.cluster.local:9090`) to reach another in-cluster service.

## 7) Explore Prometheus metrics in Grafana

Open Grafana's Explore view, select Prometheus as the data source, and run queries such as:

* `up`
* `prometheus_http_requests_total`

Grafana provides:

* Richer visualizations and charting options
* Ability to combine multiple queries
* Smoother rendering and history navigation
* Dashboard sharing and alerting integrations

Example: query `prometheus_http_requests_total` to see series split by labels like `code`, `handler`, `instance`, and `job`.

## Recap

* Created a dedicated `monitoring` namespace.
* Loaded Prometheus configuration into a ConfigMap and deployed Prometheus (Deployment + Service + RBAC).
* Inspected Prometheus targets and used `up` and internal metrics such as `prometheus_http_requests_total`.
* Deployed Grafana and added Prometheus as a data source using the in-cluster Service DNS.
* Visualized Prometheus metrics from Grafana's Explore view.

This concludes the lab.

## Links and references

* Prometheus documentation: [https://prometheus.io/docs/](https://prometheus.io/docs/)
* Grafana documentation: [https://grafana.com/docs/](https://grafana.com/docs/)
* Kubernetes documentation: [https://kubernetes.io/docs/](https://kubernetes.io/docs/)

> [card] [Watch Video](https://learn.kodekloud.com/user/courses/grafana-prometheus-for-metrics-driven-observability/module/86c79392-532c-42b7-8908-18bf0a84210b/lesson/72a28ece-5c1b-46f5-b71c-15311250ce5d)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.