promtail

by ScriptonBasestar

Helm chartv0.4.0App 3.6.1

Promtail log collection agent for Loki with Kubernetes integration

About this chart

Promtail Helm Chart

Promtail log collection agent for Loki with Kubernetes integration

Features

  • DaemonSet Deployment: Runs on all nodes including masters
  • Kubernetes Service Discovery: Automatic log collection from all pods
  • Pod Metadata as Labels: namespace, pod, container, node automatically added
  • CRI/Docker Support: Parsers for containerd, cri-o, and Docker
  • Log Level Extraction: Automatic extraction of debug, info, warn, error levels
  • RBAC Support: ClusterRole for Kubernetes API access
  • Configurable Pipelines: Custom pipeline stages for log processing
  • Prometheus Metrics: Metrics endpoint for monitoring Promtail itself
  • Operational Tools: 15+ Makefile commands

TL;DR

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

# Install with default configuration
helm install my-promtail scripton-charts/promtail

# Install with custom Loki URL
helm install my-promtail scripton-charts/promtail \
  --set promtail.client.url=http://loki.monitoring.svc.cluster.local:3100/loki/api/v1/push

Prerequisites

  • Kubernetes 1.19+
  • Helm 3.0+
  • Loki instance for log storage

Configuration

Key Parameters

ParameterDescriptionDefault
promtail.client.urlLoki push URLhttp://loki:3100/loki/api/v1/push
promtail.server.logLevelLog levelinfo
promtail.kubernetesSD.addPodAnnotationsAdd pod annotations as labelsfalse
promtail.pipelineStages.cri.enabledEnable CRI parsertrue
promtail.pipelineStages.docker.enabledEnable Docker parserfalse
rbac.createCreate RBAC resourcestrue
service.enabledEnable service for metricstrue

Operational Commands

# View logs from all Promtail pods
make -f make/ops/promtail.mk promtail-logs

# View logs from specific node
make -f make/ops/promtail.mk promtail-logs-node NODE=node-name

# Shell into Promtail pod
make -f make/ops/promtail.mk promtail-shell

# Check DaemonSet status
make -f make/ops/promtail.mk promtail-status

# View configuration
make -f make/ops/promtail.mk promtail-config

# Show scrape targets
make -f make/ops/promtail.mk promtail-targets

# Test Loki connection
make -f make/ops/promtail.mk promtail-test-loki

# Debug information
make -f make/ops/promtail.mk promtail-debug

# List nodes running Promtail
make -f make/ops/promtail.mk promtail-list-nodes

Production Setup

# values-prod.yaml
promtail:
  client:
    url: "http://loki.monitoring.svc.cluster.local:3100/loki/api/v1/push"
    externalLabels:
      cluster: "production"
      environment: "prod"

  kubernetesSD:
    addPodAnnotations: false  # Reduce label cardinality

  pipelineStages:
    cri:
      enabled: true
    custom:
      # Drop debug logs in production
      - match:
          selector: '{level="debug"}'
          action: drop
      # Sample info logs (keep 50%)
      - match:
          selector: '{level="info"}'
          action: keep
        sampling:
          rate: 0.5

resources:
  limits:
    cpu: 500m
    memory: 256Mi
  requests:
    cpu: 200m
    memory: 128Mi

# Use high priority to ensure logs are always collected
priorityClassName: "system-node-critical"

How It Works

Log Collection Flow

  1. Discovery: Promtail uses Kubernetes API to discover all pods
  2. Read Logs: Reads logs from /var/log/pods/*
  3. Parse: Applies CRI/Docker parser to extract log line
  4. Extract: Extracts log level (debug, info, warn, error, fatal, panic)
  5. Label: Adds Kubernetes metadata as Loki labels
  6. Push: Sends logs to Loki via HTTP

Kubernetes Labels Added

Automatically added to all logs:

  • namespace: Kubernetes namespace
  • pod: Pod name
  • container: Container name
  • node: Node name
  • All pod labels (prefixed with label_)

Example LogQL Query

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

# Error logs from specific pod
{namespace="production",pod="myapp-12345",level="error"}

# All logs from containers with specific label
{label_app="myapp"}

Log Parsers

CRI Parser (Default)

For containerd and cri-o runtimes:

promtail:
  pipelineStages:
    cri:
      enabled: true

CRI log format:

2023-01-01T10:00:00.000Z stderr F This is the log message

Docker Parser

For Docker runtime:

promtail:
  pipelineStages:
    cri:
      enabled: false
    docker:
      enabled: true

Docker log format:

{"log":"This is the log message\n","stream":"stderr","time":"2023-01-01T10:00:00.000Z"}

Custom Pipeline Stages

Add custom processing to logs:

promtail:
  pipelineStages:
    custom:
      # Extract JSON fields
      - json:
          expressions:
            level: level
            message: message

      # Parse timestamp
      - timestamp:
          source: timestamp
          format: RFC3339

      # Add static label
      - static_labels:
          environment: production

      # Drop noisy logs
      - match:
          selector: '{container="sidecar"}'
          action: drop

      # Sample logs (keep 10%)
      - match:
          selector: '{level="debug"}'
          action: keep
        sampling:
          rate: 0.1

Label Cardinality

Important: Loki performance depends heavily on label cardinality.

Good Labels (Low Cardinality)

  • namespace (~10-100 unique values)
  • container (~10-50 unique values)
  • level (~5-10 unique values)
  • app label (~10-100 unique values)

Bad Labels (High Cardinality)

  • Pod names (1000s of unique values)
  • Request IDs (millions of unique values)
  • Timestamps (infinite cardinality)

Best Practice: Use labels for filtering, use LogQL for searching within log lines.

Disable Pod Annotations

Pod annotations can add high cardinality:

promtail:
  kubernetesSD:
    addPodAnnotations: false  # Recommended for production

Basic Authentication

If Loki requires authentication:

promtail:
  client:
    url: "https://loki.example.com/loki/api/v1/push"
    basicAuth:
      enabled: true
      username: "promtail"
      password: "secret"

Multi-Tenancy

For Loki multi-tenancy:

promtail:
  client:
    url: "http://loki:3100/loki/api/v1/push"
    tenantId: "team-a"

Additional Scrape Configs

Collect logs from other sources:

promtail:
  additionalScrapeConfigs:
    # Syslog
    - job_name: syslog
      syslog:
        listen_address: 0.0.0.0:1514
      relabel_configs:
        - source_labels: ['__syslog_message_hostname']
          target_label: 'host'

    # Journal
    - job_name: journal
      journal:
        max_age: 12h
        labels:
          job: systemd-journal
      relabel_configs:
        - source_labels: ['__journal__systemd_unit']
          target_label: 'unit'

Resource Requirements

Development

resources:
  limits:
    cpu: 200m
    memory: 128Mi
  requests:
    cpu: 50m
    memory: 32Mi

Production

resources:
  limits:
    cpu: 500m
    memory: 256Mi
  requests:
    cpu: 200m
    memory: 128Mi

Troubleshooting

Check Promtail Status

make -f make/ops/promtail.mk promtail-status

View Logs

make -f make/ops/promtail.mk promtail-logs

Test Loki Connection

make -f make/ops/promtail.mk promtail-test-loki

Check Targets

make -f make/ops/promtail.mk promtail-targets

Debug Information

make -f make/ops/promtail.mk promtail-debug

Check Log Paths

make -f make/ops/promtail.mk promtail-check-logs-path

Common Issues

Issue: Promtail not collecting logs

Solution:

  1. Check if pods are running: make -f make/ops/promtail.mk promtail-status
  2. Check if Loki is reachable: make -f make/ops/promtail.mk promtail-test-loki
  3. Verify log paths are mounted: make -f make/ops/promtail.mk promtail-check-logs-path

Issue: Logs not appearing in Loki

Solution:

  1. Check Promtail logs for errors: make -f make/ops/promtail.mk promtail-logs
  2. Verify Loki URL is correct: make -f make/ops/promtail.mk promtail-config
  3. Check Loki is receiving logs: Query {namespace="default"} in Grafana

Issue: High memory usage

Solution:

  1. Reduce log collection with pipeline stages
  2. Increase resources.limits.memory
  3. Sample or drop debug logs in production

Integration with Grafana

Add Loki to Grafana

  1. Navigate to Configuration → Data Sources
  2. Click "Add data source"
  3. Select "Loki"
  4. URL: http://loki.default.svc.cluster.local:3100
  5. Save & Test

Example Queries

# View all logs from namespace
{namespace="production"}

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

# Logs from specific app
{label_app="myapp"}

# Rate of error logs
rate({namespace="production"} |= "error" [5m])

Backup & Recovery

Promtail is a stateless log shipping agent that does not store logs persistently. Backup focuses on configuration and positions file.

Backup Strategy

ComponentPrioritySizeRecovery Time
ConfigurationCritical< 10 KB< 5 minutes
Positions FileImportant< 1 MB< 10 minutes
Kubernetes ManifestsCritical< 50 KB< 15 minutes

RTO/RPO Targets:

  • RTO (Recovery Time): < 30 minutes
  • RPO (Recovery Point): 0 (stateless, no data loss)

Quick Backup Commands

# 1. Backup ConfigMap
kubectl get configmap -n default promtail-config -o yaml > promtail-config-backup.yaml

# 2. Backup Helm values
helm get values my-promtail -n default > promtail-values-backup.yaml

# 3. Backup Kubernetes manifests
helm get manifest my-promtail -n default > promtail-manifest-backup.yaml

# 4. Backup positions file (optional)
POD=$(kubectl get pods -n default -l app.kubernetes.io/name=promtail -o jsonpath='{.items[0].metadata.name}')
kubectl exec -n default $POD -- cat /run/promtail/positions.yaml > positions-backup.yaml

Backup Methods

1. ConfigMap Export (Recommended)

Export Promtail ConfigMap via kubectl:

kubectl get configmap -n default promtail-config -o yaml > promtail-config-backup.yaml

Pros: Simple, fast, version-controllable Cons: Manual execution

2. Git-Based Configuration Management (Best Practice)

Store values.yaml in Git repository:

# Deploy from Git
helm install my-promtail scripton-charts/promtail \
  -f https://raw.githubusercontent.com/myorg/promtail-config/main/values.yaml

Pros: Automatic version control, audit trail Cons: Requires Git setup

3. Positions File Backup (Optional)

Copy positions file from each Promtail pod:

PODS=$(kubectl get pods -n default -l app.kubernetes.io/name=promtail -o jsonpath='{.items[*].metadata.name}')
for POD in $PODS; do
  kubectl exec -n default $POD -- cat /run/promtail/positions.yaml > positions-$POD.yaml
done

Note: Positions file prevents re-ingesting logs. If lost, Promtail will start reading from current position.

Recovery Procedures

Configuration-Only Recovery

Restore Promtail ConfigMap:

# Restore ConfigMap
kubectl apply -f promtail-config-backup.yaml

# Restart Promtail pods
kubectl rollout restart daemonset/my-promtail -n default
kubectl rollout status daemonset/my-promtail -n default

RTO: < 5 minutes

Full Cluster Recovery

Reinstall Promtail using backed-up Helm values:

# Install from backup
helm install my-promtail scripton-charts/promtail \
  -f promtail-values-backup.yaml \
  -n default

# Verify deployment
kubectl get daemonset -n default my-promtail
kubectl get pods -n default -l app.kubernetes.io/name=promtail

RTO: < 15 minutes

Automated Backup (CronJob)

Deploy CronJob for daily configuration backups:

apiVersion: batch/v1
kind: CronJob
metadata:
  name: promtail-backup
  namespace: default
spec:
  schedule: "0 2 * * *"  # Daily at 2 AM
  jobTemplate:
    spec:
      template:
        spec:
          serviceAccountName: promtail-backup
          containers:
          - name: backup
            image: bitnami/kubectl:latest
            command:
            - /bin/sh
            - -c
            - |
              TIMESTAMP=$(date +%Y%m%d-%H%M%S)
              kubectl get configmap -n default promtail-config -o yaml \
                > /backups/promtail/config-$TIMESTAMP.yaml
            volumeMounts:
            - name: backup-storage
              mountPath: /backups
          restartPolicy: OnFailure
          volumes:
          - name: backup-storage
            persistentVolumeClaim:
              claimName: promtail-backup-pvc

For complete backup procedures and disaster recovery strategies, see Promtail Backup Guide.


Security & RBAC

Promtail requires cluster-wide permissions to read pod logs from all nodes.

RBAC Resources

This chart creates the following RBAC resources:

  • ServiceAccount: Pod identity for Promtail DaemonSet
  • ClusterRole: Cluster-wide permissions for log collection
  • ClusterRoleBinding: Links ServiceAccount to ClusterRole

Permissions Granted:

  • Read access to Nodes, Pods, Services, Endpoints (for service discovery)
  • Read pod logs across all namespaces (required for log shipping)

Configuration

rbac:
  # Create RBAC resources
  create: true
  # Annotations to add to the ClusterRole and ClusterRoleBinding
  annotations:
    description: "Promtail log shipping agent"

Security Best Pra

Deploy promtail with OpenTenant

Each tenant gets its own release of this chart, with its own namespace, secrets and domain. The builder below already has promtail 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 chartpromtail 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