Helm chartv0.4.0App 3.6.1

Loki log aggregation system with Grafana integration

About this chart

Loki Helm Chart

Loki log aggregation system with Grafana integration for Kubernetes

Features

  • Flexible Storage: Filesystem (default) or S3-compatible object storage
  • High Availability: StatefulSet with memberlist gossip protocol
  • Grafana Integration: Native LogQL support for log queries
  • Replication: Configurable replication factor for data redundancy
  • Persistent Storage: PVC for local chunks and index
  • Health Probes: Liveness and readiness checks
  • Operational Tools: 20+ Makefile commands

TL;DR

helm repo add scripton-charts https://scriptonbasestar-container.github.io/sb-helm-charts
helm repo update

# Install with filesystem storage (development)
helm install my-loki scripton-charts/loki

# Install with S3 storage (production)
helm install my-loki scripton-charts/loki \
  --set loki.storage.type=s3 \
  --set loki.storage.s3.endpoint=s3.amazonaws.com \
  --set loki.storage.s3.bucketNames=loki-chunks \
  --set loki.storage.s3.accessKeyId=AKIAIOSFODNN7EXAMPLE \
  --set loki.storage.s3.secretAccessKey=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY \
  --set replicaCount=3 \
  --set loki.replicationFactor=3

Prerequisites

  • Kubernetes 1.19+
  • Helm 3.0+
  • PV provisioner (for persistence)
  • S3-compatible storage (for production S3 mode)

Configuration

Key Parameters

ParameterDescriptionDefault
replicaCountNumber of Loki replicas1
loki.storage.typeStorage backend (filesystem/s3)filesystem
loki.storage.s3.endpointS3 endpoint""
loki.storage.s3.bucketNamesS3 bucket name""
loki.replicationFactorReplication factor1
loki.limits.ingestionRateMBIngestion rate limit (MB)4
persistence.enabledEnable persistencetrue
persistence.sizePVC size10Gi

Operational Commands

# View logs
make -f make/ops/loki.mk loki-logs

# Port forward
make -f make/ops/loki.mk loki-port-forward

# Check readiness
make -f make/ops/loki.mk loki-ready

# Get ring status
make -f make/ops/loki.mk loki-ring-status

# Query logs
make -f make/ops/loki.mk loki-query QUERY='{job="app"}' TIME=5m

# Get all labels
make -f make/ops/loki.mk loki-labels

# Send test log
make -f make/ops/loki.mk loki-test-push

# Get Grafana datasource URL
make -f make/ops/loki.mk loki-grafana-datasource

# Scale replicas
make -f make/ops/loki.mk loki-scale REPLICAS=3

Production Setup

Filesystem Storage (Small Scale)

# values-filesystem-prod.yaml
replicaCount: 2

loki:
  storage:
    type: "filesystem"
  replicationFactor: 2

persistence:
  storageClass: "fast-ssd"
  size: 100Gi

resources:
  limits:
    cpu: 2000m
    memory: 2Gi
  requests:
    cpu: 500m
    memory: 1Gi

S3 Storage (Large Scale)

# values-s3-prod.yaml
replicaCount: 3

loki:
  storage:
    type: "s3"
    s3:
      endpoint: "s3.amazonaws.com"
      bucketNames: "loki-chunks"
      region: "us-east-1"
      accessKeyId: "AKIAIOSFODNN7EXAMPLE"
      secretAccessKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
      s3ForcePathStyle: false
  replicationFactor: 3
  limits:
    ingestionRateMB: 8
    ingestionBurstSizeMB: 12

persistence:
  storageClass: "fast-ssd"
  size: 50Gi

affinity:
  podAntiAffinity:
    requiredDuringSchedulingIgnoredDuringExecution:
      - labelSelector:
          matchExpressions:
            - key: app.kubernetes.io/name
              operator: In
              values:
                - loki
        topologyKey: kubernetes.io/hostname

Grafana Integration

Add Loki as Data Source

  1. Via UI:

    • Navigate to Configuration → Data Sources
    • Click "Add data source"
    • Select "Loki"
    • URL: http://loki.default.svc.cluster.local:3100
  2. Via API:

make -f make/ops/loki.mk loki-grafana-datasource
  1. Query Logs:
    • Use LogQL syntax in Grafana Explore
    • Example: {namespace="production"} |= "error"

Log Shipping

Promtail Configuration

# promtail-config.yaml
clients:
  - url: http://loki.default.svc.cluster.local:3100/loki/api/v1/push

scrape_configs:
  - job_name: kubernetes-pods
    kubernetes_sd_configs:
      - role: pod
    relabel_configs:
      - source_labels: [__meta_kubernetes_pod_name]
        target_label: pod
      - source_labels: [__meta_kubernetes_namespace]
        target_label: namespace

Fluent Bit Configuration

[OUTPUT]
    Name        loki
    Match       *
    Host        loki.default.svc.cluster.local
    Port        3100
    Labels      job=fluentbit

LogQL Query Examples

# All logs from a namespace
{namespace="production"}

# Error logs
{namespace="production"} |= "error"

# Rate of errors per minute
rate({namespace="production"} |= "error" [1m])

# Logs matching regex pattern
{namespace="production"} |~ "user \\d+ logged in"

# Logs from specific pod
{pod="myapp-12345"}

# JSON parsing
{namespace="production"} | json | line_format "{{.message}}"

Storage Backends

Filesystem Storage

  • Use Case: Development, small deployments
  • Pros: Simple setup, no external dependencies
  • Cons: Limited scalability, single-node storage

S3-Compatible Storage

  • Use Case: Production, large-scale deployments
  • Pros: Unlimited storage, cost-effective, HA
  • Cons: Network latency, S3 costs
  • Compatible Services: AWS S3, MinIO, Ceph, GCS, Azure Blob

High Availability

For HA deployment:

  1. Set replicas ≥ 3:

    replicaCount: 3
    loki:
      replicationFactor: 3
    
  2. Use S3 storage:

    loki:
      storage:
        type: "s3"
    
  3. Enable pod anti-affinity:

    affinity:
      podAntiAffinity:
        requiredDuringSchedulingIgnoredDuringExecution:
          - labelSelector:
              matchExpressions:
                - key: app.kubernetes.io/name
                  operator: In
                  values:
                    - loki
            topologyKey: kubernetes.io/hostname
    

Backup & Recovery Strategy

Overview

Loki backup strategy varies by storage backend:

Storage TypeComponentsRTORPOComplexity
FilesystemConfig + PVC snapshot< 1 hour1 hourMedium
S3Config + S3 versioning< 10 minutes0 (continuous)Low

Backup Components

  1. Configuration - ConfigMap, Secrets (RTO: < 5 min, RPO: 0)
  2. Log Data - Chunks (filesystem: hourly, S3: continuous)
  3. Index - BoltDB/TSDB index files (hourly, rebuildable)
  4. PVC - Full volume snapshot (weekly, filesystem mode only)

Quick Backup Commands

# Full backup (config + data + index)
make -f make/ops/loki.mk loki-backup-all

# Configuration only
make -f make/ops/loki.mk loki-backup-config

# Data only (chunks + index)
make -f make/ops/loki.mk loki-backup-data

# PVC snapshot (filesystem mode)
make -f make/ops/loki.mk loki-backup-pvc-snapshot

# Verify backup
make -f make/ops/loki.mk loki-backup-verify BACKUP_FILE=/path/to/backup

Quick Recovery Commands

# Full recovery
make -f make/ops/loki.mk loki-restore-all BACKUP_FILE=/path/to/backup

# Configuration only
make -f make/ops/loki.mk loki-restore-config BACKUP_FILE=/path/to/config

# Data only
make -f make/ops/loki.mk loki-restore-data BACKUP_FILE=/path/to/data

Backup Automation

# CronJob for hourly backups
apiVersion: batch/v1
kind: CronJob
metadata:
  name: loki-backup
spec:
  schedule: "0 */6 * * *"  # Every 6 hours
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: backup
            image: bitnami/kubectl:latest
            command:
            - /bin/bash
            - -c
            - |
              kubectl exec -n monitoring loki-0 -- \
                wget -qO- -X POST http://localhost:3100/flush
              # Backup chunks and index
              kubectl exec -n monitoring loki-0 -- \
                tar czf - /loki | aws s3 cp - s3://backups/loki-$(date +%Y%m%d).tar.gz

Detailed documentation: Loki Backup Guide


Upgrading

Upgrade Strategies

StrategyDowntimeComplexityRecommended For
Rolling UpgradeNone (HA)LowProduction
Blue-Green10-30 minMediumLarge deployments
Maintenance Window15-30 minLowDev/test

Pre-Upgrade Checklist

# 1. Run pre-upgrade validation
make -f make/ops/loki.mk loki-pre-upgrade-check

# 2. Create backup
make -f make/ops/loki.mk loki-backup-all

# 3. Review release notes
echo "Check: https://github.com/grafana/loki/releases"

Rolling Upgrade (Zero Downtime)

Prerequisites: replicaCount ≥ 2, S3 storage recommended

# 1. Update Helm repository
helm repo update scripton-charts

# 2. Upgrade with new version
helm upgrade loki scripton-charts/loki \
  --set image.tag=3.7.0 \
  --reuse-values \
  --wait \
  --timeout=10m

# 3. Verify upgrade
make -f make/ops/loki.mk loki-post-upgrade-check

Maintenance Window Upgrade

# 1. Backup first
make -f make/ops/loki.mk loki-backup-all

# 2. Scale down
kubectl scale statefulset loki -n monitoring --replicas=0

# 3. Upgrade
helm upgrade loki scripton-charts/loki \
  --set image.tag=3.7.0 \
  --reuse-values

# 4. Scale up
kubectl scale statefulset loki -n monitoring --replicas=1

# 5. Verify
make -f make/ops/loki.mk loki-ready

Version-Specific Notes

Loki 2.x → 3.0 (Breaking Changes)

Schema changes:

# Update schema_config in values.yaml
loki:
  config:
    schema_config:
      configs:
        - from: 2020-10-24
          store: tsdb        # Changed from boltdb-shipper
          schema: v12        # Changed from v11
          object_store: filesystem

Configuration updates:

  • storage_config.boltdb_shipper → storage_config.tsdb_shipper
  • Index format changed from BoltDB to TSDB
  • Query frontend configuration simplified

Loki 3.0 → 3.6 (Minor Changes)

  • No breaking changes
  • Improved query performance
  • Enhanced TSDB support
  • Optional: Enable structured metadata

Loki 3.6 → 3.7 (Patch Updates)

  • Straightforward rolling upgrade
  • New features: log volume endpoint
  • Bug fixes and stability improvements

Post-Upgrade Validation

# Automated validation (8 checks)
make -f make/ops/loki.mk loki-post-upgrade-check

# Manual verification
kubectl get pods -n monitoring -l app.kubernetes.io/name=loki
kubectl exec -n monitoring loki-0 -- /usr/bin/loki --version
make -f make/ops/loki.mk loki-query QUERY='{job="loki"}' TIME=5m

Rollback

# Method 1: Helm rollback
make -f make/ops/loki.mk loki-upgrade-rollback

# Method 2: Restore from backup
make -f make/ops/loki.mk loki-restore-all BACKUP_FILE=/path/to/backup

# Method 3: Revert image tag
helm upgrade loki scripton-charts/loki \
  --set image.tag=3.6.1 \
  --reuse-values

Detailed documentation: Loki Upgrade Guide


Security & RBAC

ServiceAccount Permissions

Loki ServiceAccount has minimal permissions:

  • Read ConfigMaps (configuration)
  • Read Secrets (S3 credentials)

RBAC Configuration

rbac:
  create: true
  annotations: {}

Security Best Practices

  1. Enable authentication:

    loki:
      auth:
        enabled: true
    
  2. Use S3 encryption:

    loki:
      storage:
        s3:
          sse_enabled: true
    
  3. Restrict network access:

    # NetworkPolicy example
    apiVersion: networking.k8s.io/v1
    kind: NetworkPolicy
    metadata:
      name: loki-network-policy
    spec:
      podSelector:
        matchLabels:
          app.kubernetes.io/name: loki
      policyTypes:
      - Ingress
      ingress:
      - from:
        - podSelector:
            matchLabels:
              app: promtail  # Only allow Promtail
        ports:
        - protocol: TCP
          port: 3100
    

Operations & Maintenance

Health Monitoring

# Comprehensive health check
make -f make/ops/loki.mk loki-health-check

# Check readiness
make -f make/ops/loki.mk loki-ready

# View metrics
make -f make/ops/loki.mk loki-metrics

Performance Tuning

For high-volume environments:

loki:
  limits:
    ingestionRateMB: 8
    ingestionBurstSizeMB: 12
    max_query_parallelism: 32

resources:
  limits:
    cpu: 2000m
    memory: 4Gi
  requests:
    cpu: 500m
    memory: 2Gi

For query-heavy workloads:

loki:
  config:
    query_range:
      results_cache:
        cache:
          enable_fifocache: true
          fifocache:
            max_size_bytes: 1GB

Storage Management

Check storage usage:

make -f make/ops/loki.mk loki-check-storage

Configure retention (reduce storage):

loki:
  limits:
    retention_period: 168h  # 7 days

S3 lifecycle policy:

# Move old data to Glacier after 30 days
aws s3api put-bucket-lifecycle-configuration \
  --bucket loki-chunks \
  --lifecycle-configuration file://lifecycle.json

Scaling

Vertical scaling:

resources:
  limits:
    memory: 4Gi  # Increase for more data
    cpu: 2000m

Horizontal scaling:

# Scale to 3 replicas
make -f make/ops/loki.mk loki-scale REPLICAS=3

# Enable replication
loki:
  replicationFactor: 3

Monitoring & Diagnostics

Metrics

Loki exposes Prometheus metrics on port 3100:

# Get all metrics
make -f make/ops/loki.mk loki-metrics

# Key metrics to monitor:
# - 

Deploy loki with OpenTenant

Each tenant gets its own release of this chart, with its own namespace, secrets and domain. The builder below already has loki on a Hetzner server. Change the host, add apps from the marketplace, then copy the generated files. Providers and prices are samples, and nothing here is sent anywhere.

  1. Pick a serverConnect Hetzner, OVHcloud or AWS. The builder starts on Hetzner, the cheapest sample rate.
  2. Place the chartloki is pinned at v0.4.0 in opentenant.yaml. Drag more apps from the marketplace onto a rack.
  3. ApplySave opentenant.yaml and main.tf from the console, then run the commands below.
# opentenant.yaml, main.tf and dns.tf come from the builder below
opentenant validate opentenant.yaml
terraform init && terraform apply