Skip to content

Ship Linux and Container Logs to Loki with Grafana Alloy

Install Grafana Alloy, write a config that tails files, journald, and container output, keep label cardinality in check, run it under systemd, and confirm ingestion with LogQL — the practical path off end-of-life Promtail.

Promtail is end of life. Grafana deprecated it and points every new Loki deployment at Grafana Alloy, its OpenTelemetry Collector distribution, which does the same log shipping through a different configuration language. If you have been asked to get /var/log, the systemd journal, and container output into Loki on a fleet of Linux hosts — or to migrate a Promtail config that already works — this walks the whole path: installing the package, writing config.alloy component by component, deciding what becomes a label and what does not, running it under systemd, reading the built-in UI on port 12345, and proving with a LogQL query that the lines actually landed. The configuration language is the real change. Promtail’s YAML described a list of scrape jobs; Alloy describes named components that reference each other’s exports, so the pipeline is a graph you wire by name rather than a list you nest.

What you’ll accomplish

  • Install Alloy from Grafana’s package repository and have it running under systemd as the alloy user.
  • Tail plain log files, the systemd journal, and Docker container output from one config file.
  • Parse JSON lines, promote a small set of fields to labels, and push the high-cardinality ones to structured metadata instead.
  • Reach the Alloy UI on 127.0.0.1:12345 to see component health and live pipeline data.
  • Confirm end to end that entries are in Loki, with a stream count you can defend and a LogQL query that returns them.

Prerequisites

  • A Loki instance you can reach over HTTP, version 3.x. Structured metadata — used below to hold request IDs — requires Loki 3.0 or newer. On Loki 2.x, drop that stage and leave those fields in the log body. If you still need to stand Loki up, start with deploying Loki for log aggregation.
  • A Debian, Ubuntu, RHEL, or Rocky host with systemd and root access. The commands below use apt; the RPM path is the same idea with https://rpm.grafana.com as the repository and dnf install alloy.
  • Grafana 10 or newer with the Loki data source configured, for the verification step.
  • Honest version caveat: Alloy’s component set has grown steadily since 1.0. Everything here uses components that have been stable since early releases, but argument names do occasionally gain optional fields — check alloy fmt output against your installed version rather than assuming.
  • If journald is running with volatile storage, its files live in /run/log/journal, not /var/log/journal. Check Storage= in /etc/systemd/journald.conf before you set a path.

How it works

Alloy runs as a single process holding a graph of components. Each component has a type, a user-chosen label, arguments, and exports. You wire the pipeline by referring to one component’s export from another component’s argument — forward_to = [loki.process.varlogs.receiver] is what connects a source to a processor. There is no ordering to get right in the file; Alloy resolves the graph itself and refuses to start on a cycle or a dangling reference.

Diagram of the Alloy log pipeline: file, journal, and Docker sources feeding loki.process, then loki.write, then Loki and Grafana

A log path is normally four components. local.file_match turns a glob into a target list. loki.source.file tails those targets and emits entries. loki.process runs the entries through ordered stages that parse and mutate them. loki.write batches and pushes over HTTP to Loki’s push API. Journal and container sources skip the discovery step because loki.source.journal and loki.source.docker find their own input.

The part that decides whether this deployment ages well is what you attach as a label. Loki indexes labels and nothing else; the set of label key-value pairs on an entry defines its stream. Two labels with 50 and 100 possible values produce up to 5,000 streams. Add a request_id label and you get one stream per request, which is how a working cluster becomes an unqueryable one in an afternoon.

Diagram showing bounded fields becoming labels, per-request identifiers becoming structured metadata, and everything else staying in the log line

Loki 3 gives you a middle tier for this. Structured metadata attaches key-value pairs to individual entries without creating streams, so a trace or request ID stays queryable without touching the index.

Step-by-step

  1. Install Alloy from Grafana’s repository.

    sudo apt-get install -y gpg wget
    sudo mkdir -p /etc/apt/keyrings/
    wget -q -O - https://apt.grafana.com/gpg.key | gpg --dearmor | sudo tee /etc/apt/keyrings/grafana.gpg > /dev/null
    echo "deb [signed-by=/etc/apt/keyrings/grafana.gpg] https://apt.grafana.com stable main" | sudo tee /etc/apt/sources.list.d/grafana.list
    sudo apt-get update
    sudo apt-get install -y alloy
    alloy --version

    Success signal: alloy --version prints a line beginning alloy, version 1. followed by build metadata. The package creates the alloy user, /etc/alloy/config.alloy, the environment file /etc/default/alloy, and the state directory /var/lib/alloy/data.

  2. Define the writer first. Replace the contents of /etc/alloy/config.alloy. Everything else will forward into this component.

    // /etc/alloy/config.alloy
    loki.write "default" {
      endpoint {
        url = "http://loki.internal:3100/loki/api/v1/push"
      }
    
      external_labels = {
        env     = "prod",
        cluster = "ca-central-1",
      }
    }

    external_labels are stamped onto every entry this writer sends. Keep them to values that are constant for the host — environment, cluster, region. If Loki is behind authentication, add a basic_auth block inside endpoint and read the secret with env("LOKI_PASSWORD") rather than writing it in the file.

  3. Tail log files. local.file_match expands the glob on a timer, so files created after Alloy starts are picked up without a restart.

    local.file_match "varlogs" {
      path_targets = [{
        __path__ = "/var/log/*.log",
        job      = "varlogs",
        host     = constants.hostname,
      }]
      sync_period = "10s"
    }
    
    loki.source.file "varlogs" {
      targets       = local.file_match.varlogs.targets
      forward_to    = [loki.process.varlogs.receiver]
      tail_from_end = true
    }

    constants.hostname is a built-in, so the same file deploys to every host unchanged. tail_from_end = true means a first start reads only new lines instead of replaying whatever history is on disk — usually what you want, because Loki will reject entries older than its reject_old_samples_max_age.

  4. Add the processing stages. Order matters here, and it is the one place in the file where it does: parse, then label, then attach metadata, then set the output.

    loki.process "varlogs" {
      forward_to = [loki.write.default.receiver]
    
      stage.json {
        expressions = {
          level      = "level",
          service    = "service",
          request_id = "request_id",
          msg        = "msg",
        }
      }
    
      stage.labels {
        values = {
          level   = "",
          service = "",
        }
      }
    
      stage.structured_metadata {
        values = {
          request_id = "",
        }
      }
    
      stage.output {
        source = "msg"
      }
    }

    stage.json extracts fields into a temporary map. stage.labels promotes two of them — level has maybe six values, service maybe thirty. request_id is extracted but deliberately never reaches stage.labels; it goes to structured metadata. stage.output replaces the stored line with just the message, which is only safe when every line in this job is JSON. For a mixed source, wrap the JSON stages in a stage.match block with a selector, or drop stage.output and keep the raw line.

  5. Add the systemd journal. Relabelling for journal entries is expressed as a separate loki.relabel component whose rules you reference; forward_to = [] tells Alloy this component exists only to export rules.

    loki.relabel "journal" {
      forward_to = []
    
      rule {
        source_labels = ["__journal__systemd_unit"]
        target_label  = "unit"
      }
      rule {
        source_labels = ["__journal__hostname"]
        target_label  = "host"
      }
      rule {
        source_labels = ["__journal_priority_keyword"]
        target_label  = "level"
      }
      rule {
        source_labels = ["unit"]
        regex         = "session-.*|user@.*"
        action        = "drop"
      }
    }
    
    loki.source.journal "host" {
      path          = "/var/log/journal"
      max_age       = "12h"
      relabel_rules = loki.relabel.journal.rules
      labels        = { job = "systemd-journal" }
      forward_to    = [loki.write.default.receiver]
    }

    That last drop rule matters more than it looks. Without it, every SSH login creates a session-NNN.scope unit and therefore a new stream, and a busy bastion host manufactures thousands of dead streams a week.

    Grant the journal read permission and confirm it:

    sudo usermod -a -G adm,systemd-journal alloy
    sudo -u alloy journalctl -n 1 --no-pager

    Expected output: one recent journal line. A No journal files were found or permissions error here means Alloy will silently ship nothing from this source.

  6. Add container logs. Discovery and tailing are separate components, and the relabel rules are shared between them.

    discovery.docker "containers" {
      host             = "unix:///var/run/docker.sock"
      refresh_interval = "10s"
    }
    
    discovery.relabel "containers" {
      targets = discovery.docker.containers.targets
    
      rule {
        source_labels = ["__meta_docker_container_name"]
        regex         = "/(.*)"
        target_label  = "container"
      }
      rule {
        source_labels = ["__meta_docker_container_label_com_docker_compose_service"]
        target_label  = "service"
      }
    }
    
    loki.source.docker "containers" {
      host          = "unix:///var/run/docker.sock"
      targets       = discovery.relabel.containers.output
      labels        = { job = "docker" }
      relabel_rules = discovery.relabel.containers.rules
      forward_to    = [loki.write.default.receiver]
    }

    Note what is not labelled: the image tag. Labelling by image means every deploy creates a fresh set of streams. Add socket access with sudo usermod -a -G docker alloy.

  7. Check the syntax, then start it in the foreground once.

    sudo alloy fmt /etc/alloy/config.alloy
    sudo -u alloy /usr/bin/alloy run /etc/alloy/config.alloy --storage.path=/var/lib/alloy/data

    alloy fmt prints the canonically formatted config and fails loudly on a syntax error, naming the line. The foreground run is the real test: within a second you should see a line like level=info msg="now listening for http traffic" addr=127.0.0.1:12345, followed by component start messages. Any unresolved reference or bad argument stops it here with the component name in the error. Press Ctrl+C when it looks clean.

  8. Run it as a service. The package already ships alloy.service; you only adjust the environment file at /etc/default/alloy.

    CUSTOM_ARGS="--server.http.listen-addr=127.0.0.1:12345"
    RESTART_ON_UPGRADE=true

    Then enable and start:

    sudo systemctl enable --now alloy
    systemctl status alloy --no-pager
    journalctl -u alloy -n 20 --no-pager

    Expected output: Active: active (running) in the status, and journal lines ending with component startup rather than an error. Keep the listener bound to 127.0.0.1 — the UI has no authentication of its own.

  9. Open the built-in UI. From your workstation, tunnel to the host and browse to http://127.0.0.1:12345.

    ssh -N -L 12345:127.0.0.1:12345 you@web01.internal

    The UI lists every component with a health state. Click one to see its resolved arguments, its exports, and — for pipeline components — live debug data showing entries flowing through. This is the fastest way to answer “is loki.source.file finding any targets”, which the metrics endpoint cannot tell you as directly.

Validate it works

Start at the agent, then check what Loki actually accepted.

curl -fsS -o /dev/null -w '%{http_code}\n' http://127.0.0.1:12345/-/ready
curl -fsS http://127.0.0.1:12345/metrics | grep -E 'loki_write_(sent_entries|dropped_entries)_total'

Expected output: 200 from the readiness check, then counter lines where loki_write_sent_entries_total is climbing and loki_write_dropped_entries_total stays at 0. Run the second command twice a minute apart — a static sent counter means nothing is being read, and a climbing dropped counter means Loki is rejecting your writes.

Now ask Loki what it has:

curl -fsS 'http://loki.internal:3100/loki/api/v1/label/job/values' | jq -r '.data[]'
curl -fsS -G 'http://loki.internal:3100/loki/api/v1/series' \
  --data-urlencode 'match[]={job="varlogs"}' | jq '.data | length'

Expected output: the first returns varlogs, systemd-journal, and docker. The second returns the number of distinct streams under that job — single digits to low dozens is healthy. Anything in the thousands from one host means a high-cardinality field reached stage.labels.

Finally, query in Grafana Explore against the Loki data source:

{job="systemd-journal", unit="ssh.service"} |= "Accepted"

That returns successful SSH logins from the journal. Then confirm labels and structured metadata are behaving as intended:

sum by (service) (count_over_time({job="varlogs", level="error"}[5m]))
{job="varlogs"} | request_id = "a3f9c1"

The first aggregates by an indexed label and should return fast. The second filters on structured metadata — a field that would have wrecked the index as a label but is still directly queryable.

Troubleshooting

too many outstanding requests when querying. This is a query-path error, not an ingest one, so nothing is wrong with Alloy. Loki’s query scheduler queue is full: raise max_outstanding_per_tenant under query_scheduler (or under frontend if you run without a scheduler). But treat the error as a symptom — it usually appears when a broad query fans out into far more subqueries than the read path can hold, which points back at either too many streams or a time range that needs narrowing.

429 responses and Maximum active stream limit exceeded. A field with unbounded values reached stage.labels. Find the culprit by listing series for the offending job with the /loki/api/v1/series call above and looking at which label varies. Move that field from stage.labels to stage.structured_metadata and restart Alloy. Note that the stream count does not drop immediately — existing streams age out with your retention period, so plan for the cluster to stay unhappy for a while after the fix.

Positions reset, so files re-ship or lines go missing. Alloy keeps read offsets under --storage.path, in a subdirectory per component. Two things reset them: wiping /var/lib/alloy/data, and renaming a component — loki.source.file "varlogs" renamed to loki.source.file "syslog" is a different component with a fresh offset. With tail_from_end = true a reset silently skips the backlog; without it, Alloy re-reads whole files and Loki rejects the duplicates. Treat the storage path as state and keep it off ephemeral disk.

Journal entries never appear. Almost always permissions or path. Confirm with sudo -u alloy journalctl -n 1. If that fails, the group membership from step 5 did not take effect — group changes apply on process restart, so systemctl restart alloy is required, not just a config reload. If it succeeds but Loki still sees nothing, check that path matches where journald actually stores files.

Entries rejected as too old. max_age on loki.source.journal pulls history at startup, and Loki refuses anything older than reject_old_samples_max_age (one week by default). After an outage, a host may try to push a day of backlog and have some of it refused. Lower max_age, or accept the gap — replaying stale logs into Loki is rarely worth the ingest pressure.

When this is the wrong approach

  • You are on Kubernetes. Do not hand-write this config into a DaemonSet. Grafana’s Kubernetes monitoring Helm chart deploys Alloy with pod discovery, namespace labels, and log paths already correct, and it stays current as the API evolves. Hand-rolled node configs drift.
  • You already run an OpenTelemetry Collector fleet. Alloy is an OTel Collector distribution, but adding it means a second agent to package, version, and monitor. If your existing collectors are healthy, sending logs to Loki’s OTLP endpoint from them is less operational surface than a parallel agent.
  • You need full-text search and arbitrary field aggregation. Loki indexes labels, not content, and every unindexed filter is a scan. If your team’s core workflow is faceted search across dozens of fields, an OpenSearch or Elasticsearch cluster fits the access pattern better — at a much higher storage and operations cost.
  • One host, low volume, short retention. journalctl with a sane SystemMaxUse and a rotation policy answers most questions on a single machine. Centralized logging earns its keep at the point where you are correlating across hosts.

For the component reference and every argument these examples skip, see the Grafana Alloy documentation and the Loki documentation. If you are migrating rather than starting fresh, alloy convert --source-format=promtail will translate an existing file — compare the result against the Promtail configuration it replaces before trusting it, because the converter reproduces your old label choices faithfully, including the bad ones.

If alerts fire into an empty room after hours, that’s exactly what 24/7 Monitoring & Response closes — book a monitoring and response review.