Skip to content

Commit

Permalink
docs: getting started tutorial - Monitor K8s logs with Loki (backport…
Browse files Browse the repository at this point in the history
… k239) (#16192)

Co-authored-by: Jay Clifford <[email protected]>
  • Loading branch information
loki-gh-app[bot] and Jayclifford345 authored Feb 11, 2025
1 parent 4409783 commit d1451b0
Showing 1 changed file with 332 additions and 0 deletions.
332 changes: 332 additions & 0 deletions docs/sources/send-data/k8s-monitoring-helm/_index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,332 @@
---
title: Kubernetes Monitoring Helm tutorial
menuTitle: Kubernetes Monitoring Helm
weight: 300
description: Learn how to collect and store logs from your Kubernetes cluster using Loki.
killercoda:
title: Kubernetes Monitoring Helm
description: Learn how to collect and store logs from your Kubernetes cluster using Loki.
backend:
imageid: kubernetes-kubeadm-2nodes
---

<!-- INTERACTIVE page intro.md START -->

# Kubernetes Monitoring Helm tutorial

One of the primary use cases for Loki is to collect and store logs from your [Kubernetes cluster](https://kubernetes.io/docs/concepts/overview/). These logs fall into three categories:

1. [**Pod logs**](https://kubernetes.io/docs/concepts/cluster-administration/logging/#basic-logging-in-kubernetes): Logs generated by pods running in your cluster.
2. [**Kubernetes Events**](https://kubernetes.io/docs/reference/kubernetes-api/cluster-resources/event-v1/): Logs generated by the Kubernetes API server.
3. [**Node logs**](https://kubernetes.io/docs/concepts/cluster-administration/logging/#using-a-node-logging-agent): Logs generated by the nodes in your cluster.

{{< figure max-width="75%" src="/media/docs/loki/loki-k8s-logs.png" caption="Scraping Kubernetes Logs" alt="Scraping Kubernetes Logs" >}}

In this tutorial, we will deploy [Loki](https://grafana.com/docs/loki/latest/get-started/overview/) and the [Kubernetes Monitoring Helm chart](https://grafana.com/docs/grafana-cloud/monitor-infrastructure/kubernetes-monitoring/) to collect two of these log types: Pod logs and Kubernetes events. We will also deploy [Grafana](https://grafana.com/docs/grafana/latest/) to visualize these logs.

## Things to know

Before you begin, here are some things you should know:

* **Loki**: Loki can run in a single binary mode or as a distributed system. In this tutorial, we will deploy Loki as a single binary, otherwise known as monolithic mode. Loki can be vertically scaled in this mode depending on the number of logs you are collecting. Grafana Labs recommends running Loki in a distributed/microservice mode for production use cases to monitor high volumes of logs.
* **Deployment**: You will deploy Loki, Grafana, and Alloy (as part of the Kubernetes Monitoring Helm chart) in the `meta` namespace of your Kubernetes cluster. Make sure you have the necessary permissions to create resources in this namespace. These pods will also require resources to run, so consider the amount of capacity your nodes have available. It also possible to just deploy the Kubernetes monitoring Helm chart (since it has a minimal resource footprint) within your cluster and write logs to an external Loki instance or Grafana Cloud.
* **Storage**: In this tutorial, Loki will use the default object storage backend provided in the Loki Helm chart; [MinIO](https://min.io/docs/minio/kubernetes/upstream/index.html). You should migrate to a more production-ready storage backend like [S3](https://aws.amazon.com/s3/getting-started/), [GCS](https://cloud.google.com/storage/docs), [Azure Blob Storage](https://learn.microsoft.com/en-us/azure/storage/blobs/) or a MinIO Cluster for production use cases.

<!-- INTERACTIVE ignore START -->
## Prerequisites

Before you begin, you will need the following:

* A Kubernetes cluster running version `1.23` or later.
* [kubectl](https://kubernetes.io/docs/tasks/tools/) installed on your local machine.
* [Helm](https://helm.sh/docs/intro/install/) installed on your local machine.

{{< admonition type="tip" >}}
Alternatively, you can try out this example in our interactive learning environment: [Kubernetes Monitoring with Loki](https://killercoda.com/grafana-labs/course/loki/k8s-monitoring-helm).

It's a fully configured environment with all the dependencies already installed.

![Interactive](/media/docs/loki/loki-ile.svg)

Provide feedback, report bugs, and raise issues in the [Grafana Killercoda repository](https://github.com/grafana/killercoda).
{{< /admonition >}}
<!-- INTERACTIVE ignore END -->

<!-- INTERACTIVE page intro.md END -->

<!-- INTERACTIVE page step1.md START -->

## Create the `meta` and `prod` namespaces

The K8s Monitoring Helm chart will monitor two namespaces: `meta` and `prod`:
- `meta` namespace: This namespace will be used to deploy Loki, Grafana, and Alloy.
- `prod` namespace: This namespace will be used to deploy the sample application that will generate logs.

Create the `meta` and `prod` namespaces by running the following command:

```bash
kubectl create namespace meta && kubectl create namespace prod
```

<!-- INTERACTIVE page step1.md END -->

<!-- INTERACTIVE page step2.md START -->

## Add the Grafana Helm repository

All three Helm charts (Loki, Grafana, and the Kubernetes Monitoring Helm) are available in the Grafana Helm repository. Add the Grafana Helm repository by running the following command:

```bash
helm repo add grafana https://grafana.github.io/helm-charts && helm repo update
```

As well as adding the repo to your local helm list, you should also run `helm repo update` to ensure you have the latest version of the charts.

## Clone the tutorial repository

Clone the tutorial repository by running the following command:

```bash
git clone https://github.com/grafana/alloy-scenarios.git
```

Then change directories to the `alloy-scenarios/k8s/logs` directory:

```bash
cd alloy-scenarios/k8s/logs
```

**The rest of this tutorial assumes you are in the `alloy-scenarios/k8s/logs` directory.**

<!-- INTERACTIVE page step2.md END -->

<!-- INTERACTIVE page step3.md START -->

## Deploy Loki

Grafana Loki will be used to store our collected logs. In this tutorial we will deploy Loki with a minimal footprint and use the default storage backend provided by the Loki Helm chart, MinIO.

{{< docs/ignore >}}
> **Note**: Due to the resource constraints of the Kubernetes cluster running in the playground, we are deploying Loki using a custom values file. This values file reduces the resource requirements of Loki. This turns off features such as cache and Loki Canary, and runs Loki with limited resources. This can take up to **1 minute** to complete.
{{< /docs/ignore >}}
To deploy Loki run the following command:

<!-- INTERACTIVE ignore START -->
```bash
helm install --values loki-values.yml loki grafana/loki -n meta
```
<!-- INTERACTIVE ignore END -->

{{< docs/ignore >}}

```bash
helm install --values killercoda/loki-values.yml loki grafana/loki -n meta
```
{{< /docs/ignore >}}

This command will deploy Loki in the `meta` namespace. The command also includes a `values` file that specifies the configuration for Loki. For more details on how to configure the Loki Helm chart refer to the Loki Helm [documentation](https://grafana.com/docs/loki/<LOKI_VERSION>/setup/install/helm).

<!-- INTERACTIVE page step3.md END -->

<!-- INTERACTIVE page step4.md START -->

## Deploy Grafana

Next we will deploy Grafana to the `meta` namespace. You will use Grafana to visualize the logs stored in Loki. To deploy Grafana run the following command:

```bash
helm install --values grafana-values.yml grafana grafana/grafana --namespace meta
```

As before, the command also includes a `values` file that specifies the configuration for Grafana. There are two important configuration attributes to take note of:

1. `adminUser` and `adminPassword`: These are the credentials you will use to log in to Grafana. The values are `admin` and `adminadminadmin` respectively. The recommended practice is to either use a Kubernetes secret or allow Grafana to generate a password for you. For more details on how to configure the Grafana Helm chart, refer to the Grafana Helm [documentation](https://grafana.com/docs/grafana/<GRAFANA_VERSION>/installation/helm/).

2. `datasources`: This section of the configuration lets you define the data sources that Grafana should use. In this tutorial, you will define a Loki data source. The data source is defined as follows:

```yaml
datasources:
datasources.yaml:
apiVersion: 1
datasources:
- name: Loki
type: loki
access: proxy
orgId: 1
url: http://loki-gateway.meta.svc.cluster.local:80
basicAuth: false
isDefault: false
version: 1
editable: false
```
This configuration defines a data source named `Loki` that Grafana will use to query logs stored in Loki. The `url` attribute specifies the URL of the Loki gateway. The Loki gateway is a service that sits in front of the Loki API and provides a single endpoint for ingesting and querying logs. The URL is in the format `http://loki-gateway.<NAMESPACE>.svc.cluster.local:80`. The `loki-gateway` service is created by the Loki Helm chart and is used to query logs stored in Loki. **If you choose to deploy Loki in a different namespace or with a different name, you will need to update the `url` attribute accordingly.**

<!-- INTERACTIVE page step4.md END -->

<!-- INTERACTIVE page step5.md START -->

## Deploy the Kubernetes Monitoring Helm chart

The Kubernetes Monitoring Helm chart is used for gathering, scraping, and forwarding Kubernetes telemetry data to a Grafana stack. This includes the ability to collect metrics, logs, traces, and continuous profiling data. The scope of this tutorial is to deploy the Kubernetes Monitoring Helm chart to collect pod logs and Kubernetes events.

To deploy the Kubernetes Monitoring Helm chart run the following command:

```bash
helm install --values ./k8s-monitoring-values.yml k8s grafana/k8s-monitoring -n meta
```
Within the configuration file `k8s-monitoring-values.yml` we have defined the following:

```yaml
---
cluster:
name: meta-monitoring-tutorial
destinations:
- name: loki
type: loki
url: http://loki-gateway.meta.svc.cluster.local/loki/api/v1/push
clusterEvents:
enabled: true
collector: alloy-logs
namespaces:
- meta
- prod
nodeLogs:
enabled: false
podLogs:
enabled: true
gatherMethod: kubernetesApi
collector: alloy-logs
labelsToKeep: ["app_kubernetes_io_name","container","instance","job","level","namespace","service_name","service_namespace","deployment_environment","deployment_environment_name"]
structuredMetadata:
pod: pod # Set structured metadata "pod" from label "pod"
namespaces:
- meta
- prod
# Collectors
alloy-singleton:
enabled: false
alloy-metrics:
enabled: false
alloy-logs:
enabled: true
# Required when using the Kubernetes API to pod logs
alloy:
mounts:
varlog: false
clustering:
enabled: true
alloy-profiles:
enabled: false
alloy-receiver:
enabled: false
```

To break down the configuration file:
* Define the cluster name as `meta-monitoring-tutorial`. This a static label that will be attached to all logs collected by the Kubernetes Monitoring Helm chart.
* Define a destination named `loki` that will be used to forward logs to Loki. The `url` attribute specifies the URL of the Loki gateway. **If you choose to deploy Loki in a different namespace or in a different location entirely, you will need to update the `url` attribute accordingly.**
* Enable the collection of cluster events and pod logs:
* `collector`: specifies which collector to use to collect logs. In this case, we are using the `alloy-logs` collector.
* `labelsToKeep`: specifies the labels to keep when collecting logs. Note this does not drop logs. This is useful when you do not want to apply a high cardanility label. In this case we have removed `pod` from the labels to keep.
* `structuredMetadata`: specifies the structured metadata to collect. In this case, we are setting the structured metadata `pod` so we can retain the pod name for querying. Though it does not need to be indexed as a label.zw
* `namespaces`: specifies the namespaces to collect logs from. In this case, we are collecting logs from the `meta` and `prod` namespaces.
* Disable the collection of node logs for the purpose of this tutorial as it requires the mounting of `/var/log/journal`. This is out of scope for this tutorial.
* Lastly, define the role of the collector. The Kubernetes Monitoring Helm chart will deploy only what you need and nothing more. In this case, we are telling the Helm chart to only deploy Alloy with the capability to collect logs. If you need to collect K8s metrics, traces, or continuous profiling data, you can enable the respective collectors.

<!-- INTERACTIVE page step5.md END -->

<!-- INTERACTIVE page step6.md START -->

## Accessing Grafana

To access Grafana, you will need to port-forward the Grafana service to your local machine. To do this, run the following command:

```bash
export POD_NAME=$(kubectl get pods --namespace meta -l "app.kubernetes.io/name=grafana,app.kubernetes.io/instance=grafana" -o jsonpath="{.items[0].metadata.name}") && \
kubectl --namespace meta port-forward $POD_NAME 3000 --address 0.0.0.0
```

{{< admonition type="tip" >}}
This will make your terminal unusable until you stop the port-forwarding process. To stop the process, press `Ctrl + C`.
{{< /admonition >}}

This command will port-forward the Grafana service to your local machine on port `3000`.

You can now access Grafana by navigating to [http://localhost:3000](http://localhost:3000) in your browser. The default credentials are `admin` and `adminadminadmin`.

One of the first places you should visit is Explore Logs which lets you automatically visualize and explore your logs without having to write queries:
[http://localhost:3000/a/grafana-lokiexplore-app](http://localhost:3000/a/grafana-lokiexplore-app)

{{< figure max-width="100%" src="/media/docs/loki/k8s-logs-explore-logs.png" caption="Explore Logs view of K8s logs" alt="Explore Logs view of K8s logs" >}}

<!-- INTERACTIVE page step6.md END -->

<!-- INTERACTIVE page step7.md START -->

## (Optional) View the Alloy UI

The Kubernetes Monitoring Helm chart deploys Grafana Alloy to collect and forward telemetry data from the Kubernetes cluster. The Helm chart is designed to abstract you away from creating an Alloy configuration file. However if you would like to understand the pipeline you can view the Alloy UI. To access the Alloy UI, you will need to port-forward the Alloy service to your local machine. To do this, run the following command:

```bash
export POD_NAME=$(kubectl get pods --namespace meta -l "app.kubernetes.io/name=alloy-logs,app.kubernetes.io/instance=k8s" -o jsonpath="{.items[0].metadata.name}") && \
kubectl --namespace meta port-forward $POD_NAME 12345 --address 0.0.0.0
```

{{< admonition type="tip" >}}
This will make your terminal unusable until you stop the port-forwarding process. To stop the process, press `Ctrl + C`.
{{< /admonition >}}

This command will port-forward the Alloy service to your local machine on port `12345`. You can access the Alloy UI by navigating to [http://localhost:12345](http://localhost:12345) in your browser.

{{< figure max-width="100%" src="/media/docs/loki/k8s-logs-alloy-ui.png" caption="Grafana Alloy UI" alt="Grafana Alloy UI" >}}
<!-- INTERACTIVE page step7.md END -->

<!-- INTERACTIVE page step8.md START -->

## Adding a sample application to `prod`

Finally, lets deploy a sample application to the `prod` namespace that will generate some logs. To deploy the sample application run the following command:

```bash
helm install tempo grafana/tempo-distributed -n prod
```

This will deploy a default version of Grafana Tempo to the `prod` namespace. Tempo is a distributed tracing backend that is used to store and query traces. Normally Tempo would sit alongside Loki and Grafana in the `meta` namespace, but for the purpose of this tutorial, we will pretend this is the primary application generating logs.

Once deployed lets expose Grafana once more:

```bash
export POD_NAME=$(kubectl get pods --namespace meta -l "app.kubernetes.io/name=grafana,app.kubernetes.io/instance=grafana" -o jsonpath="{.items[0].metadata.name}") && \
kubectl --namespace meta port-forward $POD_NAME 3000 --address 0.0.0.0
```

and navigate to [http://localhost:3000/a/grafana-lokiexplore-app](http://localhost:3000/a/grafana-lokiexplore-app) to view Grafana Tempo logs.

{{< figure max-width="100%" src="/media/docs/loki/k8s-logs-tempo.png" caption="Label view of Tempo logs" alt="Label view of Tempo logs" >}}

<!-- INTERACTIVE page step8.md END -->

<!-- INTERACTIVE page finish.md START -->

## Conclusion

In this tutorial, you learned how to deploy Loki, Grafana, and the Kubernetes Monitoring Helm chart to collect and store logs from a Kubernetes cluster. We have deployed a minimal test version of each of these Helm charts to demonstrate how quickly you can get started with Loki. It is now worth exploring each of these Helm charts in more detail to understand how to scale them to meet your production needs:

* [Loki Helm chart](https://grafana.com/docs/loki/<LOKI_VERSION>/setup/install/helm/)
* [Grafana Helm chart](https://grafana.com/docs/grafana/<GRAFANA_VERSION>/installation/helm/)
* [Kubernetes Monitoring Helm chart](https://grafana.com/docs/grafana-cloud/monitor-infrastructure/kubernetes-monitoring/)


<!-- INTERACTIVE page finish.md END -->


0 comments on commit d1451b0

Please sign in to comment.