Skip to content

Deploying Fluent Bit as a log shipper to multiple destinations on Ubuntu 22.04

Install Fluent Bit 3.x on Ubuntu 22.04 with structured parsers, drop/rewrite filters, and parallel outputs to Loki, Elasticsearch, and S3 — production-grade, systemd-managed, with backpressure handling.

You ship logs from twenty Ubuntu VMs into a single Elasticsearch cluster. The cluster falls over during a brownout, the agents on the VMs back up, and within fifteen minutes the agents themselves are OOM-killed because they buffered everything in RAM. When the cluster comes back the logs from the brownout window are gone — not because the cluster lost them, but because the agents never got the chance to send them. The fix isn’t a bigger Elasticsearch; it’s a shipper that knows how to spool to disk, fan out to a cheap secondary sink, and refuse to die when the primary is unreachable. Fluent Bit, configured properly, is that shipper.

What’s happening

Fluent Bit’s data path is inputs → parsers → filters → router → outputs. Inputs (tail, systemd, tcp, forward) read raw records. Parsers convert raw lines into structured fields. Filters mutate, drop, or enrich records — grep, modify, rewrite_tag, kubernetes, lua. The router examines each record’s tag and sends it to one or more outputs (loki, es, s3, forward, stdout). The outputs are independent: each one has its own retry buffer, its own filesystem spool, its own backpressure behavior. If Elasticsearch is slow but Loki is fast, the es output backs up and the loki output keeps shipping. The piece operators most often misconfigure is the storage layer — by default Fluent Bit buffers in memory, and when the memory buffer fills the input blocks, which on tail means file rotations get missed. Enable filesystem storage per-input and per-output, set per-output storage.total_limit_size, and the pipeline tolerates hours of downstream unavailability without dropping records or running the VM out of memory.

How to verify

Once the agent is running, four checks tell you whether the pipeline is healthy:

# 1. Service is up and reading the expected files
systemctl status fluent-bit --no-pager
journalctl -u fluent-bit -n 50 --no-pager

# 2. Internal metrics endpoint reports records in/out per plugin
curl -s http://127.0.0.1:2020/api/v1/metrics | jq '.input,.output'

# 3. Filesystem buffer directory exists and is not growing unbounded
du -sh /var/lib/fluent-bit/storage/ && \
  find /var/lib/fluent-bit/storage/ -type f | wc -l

# 4. Tail input is following the expected files (no stuck inodes)
curl -s http://127.0.0.1:2020/api/v1/storage | jq

The metrics endpoint shows records (in) and proc_records / errors / retries (out) per plugin. If retries is climbing on one output and not the others, that destination is the bottleneck — not Fluent Bit. If the filesystem buffer grows past its configured limit, records will start dropping at the input; raise the limit, fix the destination, or both.

The fix

Save the script as /root/setup-fluent-bit.sh, edit the destination endpoints near the top (LOKI_URL, ES_HOST, S3_BUCKET), and run as root on the Ubuntu 22.04 host that ships the logs. The installer handles base packages, the official Fluent Bit APT repository, a dedicated systemd unit with appropriate LimitNOFILE, on-disk storage layout under /var/lib/fluent-bit/storage/, per-input parsers (nginx, syslog, json, multiline app logs), a dedup-friendly filter chain (modify, grep, rewrite_tag for routing slow queries to a separate sink), and three parallel outputs (Loki for hot search, Elasticsearch for the corporate stack, S3 for archive/compliance). A health-check loop at the end verifies the agent is reading records and shipping them.

#!/usr/bin/env bash
set -euo pipefail

### Ubuntu 22.04 Fluent Bit 3.x multi-output log shipper installer
### Run as root. Edit the destination block below.
### Pipeline: tail/systemd -> parsers -> filters -> Loki + Elasticsearch + S3

if [[ "$(id -u)" -ne 0 ]]; then
  echo "Run as root."
  exit 1
fi

# === EDIT ME ===
HOSTNAME_TAG="$(hostname -s)"
ENVIRONMENT="prod"             # prod / staging / dev
LOKI_URL="https://loki.example.internal:3100/loki/api/v1/push"
LOKI_TENANT="ops"
ES_HOST="es.example.internal"
ES_PORT="9200"
ES_USER="fluentbit"
ES_PASS="CHANGE_ME_ES"
ES_INDEX="logs"
S3_BUCKET="acme-log-archive"
S3_REGION="ca-central-1"
S3_PREFIX="fluent-bit"
AWS_ACCESS_KEY_ID="CHANGE_ME_AWS_KEY"
AWS_SECRET_ACCESS_KEY="CHANGE_ME_AWS_SECRET"
# ===============

echo
echo "========================================"
echo "Fluent Bit shipper on ${HOSTNAME_TAG} (${ENVIRONMENT})"
echo "========================================"
echo

echo "==> apt update + base packages"
export DEBIAN_FRONTEND=noninteractive
apt-get update -y
apt-get install -y curl gnupg ca-certificates lsb-release jq

echo "==> Adding Fluent Bit APT repository"
curl -fsSL https://packages.fluentbit.io/fluentbit.key \
  | gpg --dearmor -o /usr/share/keyrings/fluentbit-keyring.gpg

cat > /etc/apt/sources.list.d/fluent-bit.list <<EOF
deb [signed-by=/usr/share/keyrings/fluentbit-keyring.gpg] https://packages.fluentbit.io/ubuntu/jammy jammy main
EOF

apt-get update -y
apt-get install -y fluent-bit

echo "==> Filesystem storage layout"
mkdir -p /var/lib/fluent-bit/storage \
         /var/lib/fluent-bit/buffer/loki \
         /var/lib/fluent-bit/buffer/es \
         /var/lib/fluent-bit/buffer/s3
chown -R fluent-bit:fluent-bit /var/lib/fluent-bit

echo "==> Parsers"
mkdir -p /etc/fluent-bit
cat > /etc/fluent-bit/parsers.conf <<'PARSERS'
[PARSER]
    Name        json
    Format      json
    Time_Key    time
    Time_Format %Y-%m-%dT%H:%M:%S.%L
    Time_Keep   On

[PARSER]
    Name        nginx_access
    Format      regex
    Regex       ^(?<remote>[^ ]*) (?<host>[^ ]*) (?<user>[^ ]*) \[(?<time>[^\]]*)\] "(?<method>\S+)(?: +(?<path>[^\"]*?)(?: +\S*)?)?" (?<code>[^ ]*) (?<size>[^ ]*)(?: "(?<referer>[^\"]*)" "(?<agent>[^\"]*)")?(?: (?<request_time>[^ ]*))?
    Time_Key    time
    Time_Format %d/%b/%Y:%H:%M:%S %z
    Types       code:integer size:integer request_time:float

[PARSER]
    Name        nginx_error
    Format      regex
    Regex       ^(?<time>\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2}) \[(?<level>[^\]]*)\] (?<pid>\d+)#(?<tid>\d+): (?<message>.*)$
    Time_Key    time
    Time_Format %Y/%m/%d %H:%M:%S

[PARSER]
    Name        syslog_rfc3164
    Format      regex
    Regex       ^\<(?<pri>[0-9]+)\>(?<time>[^ ]* {1,2}[^ ]* [^ ]*) (?<host>[^ ]*) (?<ident>[a-zA-Z0-9_\/\.\-]*)(?:\[(?<pid>[0-9]+)\])?(?:[^\:]*\:)? *(?<message>.*)$
    Time_Key    time
    Time_Format %b %d %H:%M:%S

[MULTILINE_PARSER]
    name          multiline_java
    type          regex
    flush_timeout 1000
    rule          "start_state"   "/(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})(.*)/"   "cont"
    rule          "cont"          "/^(?!\d{4}-\d{2}-\d{2}).+/"                    "cont"
PARSERS

echo "==> Main config"
cat > /etc/fluent-bit/fluent-bit.conf <<EOF
[SERVICE]
    Flush         5
    Daemon        Off
    Log_Level     info
    Parsers_File  parsers.conf
    Plugins_File  plugins.conf
    HTTP_Server   On
    HTTP_Listen   127.0.0.1
    HTTP_Port     2020
    storage.path                /var/lib/fluent-bit/storage
    storage.sync                normal
    storage.checksum            off
    storage.backlog.mem_limit   64M
    storage.max_chunks_up       256
    storage.metrics             On

# ---------- INPUTS ----------

[INPUT]
    Name          systemd
    Tag           host.systemd.*
    Path          /var/log/journal
    Read_From_Tail True
    Strip_Underscores True
    storage.type  filesystem
    DB            /var/lib/fluent-bit/systemd.db
    Mem_Buf_Limit 32M

[INPUT]
    Name          tail
    Tag           app.nginx.access
    Path          /var/log/nginx/access.log
    Parser        nginx_access
    DB            /var/lib/fluent-bit/nginx-access.db
    Refresh_Interval 5
    Skip_Long_Lines On
    storage.type  filesystem
    Mem_Buf_Limit 32M

[INPUT]
    Name          tail
    Tag           app.nginx.error
    Path          /var/log/nginx/error.log
    Parser        nginx_error
    DB            /var/lib/fluent-bit/nginx-error.db
    Refresh_Interval 5
    Skip_Long_Lines On
    storage.type  filesystem
    Mem_Buf_Limit 32M

[INPUT]
    Name          tail
    Tag           app.json.*
    Path          /var/log/app/*.json.log
    Parser        json
    DB            /var/lib/fluent-bit/app-json.db
    Refresh_Interval 5
    Skip_Long_Lines On
    storage.type  filesystem
    Mem_Buf_Limit 32M

[INPUT]
    Name          tail
    Tag           app.java.*
    Path          /var/log/app/*.log
    Multiline.parser multiline_java
    DB            /var/lib/fluent-bit/app-java.db
    Refresh_Interval 5
    Skip_Long_Lines On
    storage.type  filesystem
    Mem_Buf_Limit 32M

# ---------- FILTERS ----------

[FILTER]
    Name   modify
    Match  *
    Add    host          ${HOSTNAME_TAG}
    Add    environment   ${ENVIRONMENT}

[FILTER]
    Name   grep
    Match  host.systemd.*
    Exclude MESSAGE ^pam_unix\(cron:session\)
    Exclude MESSAGE ^Starting Daily apt
    Exclude MESSAGE ^Started Daily apt

[FILTER]
    Name   modify
    Match  app.nginx.access
    Rename request_time duration_seconds

# Rewrite tag for slow queries so they fan out to a separate hot sink
[FILTER]
    Name          rewrite_tag
    Match         app.nginx.access
    Rule          \$duration_seconds ^([1-9]\d*|0\.[5-9]) slow.\$TAG false
    Emitter_Name  slow_emitter

[FILTER]
    Name   modify
    Match  app.java.*
    Rename log message

[FILTER]
    Name        lua
    Match       app.*
    call        normalize
    code        function normalize(tag, ts, record) record["service"] = string.match(tag, "app%.([^%.]+)") or "unknown" return 1, ts, record end

# ---------- OUTPUTS ----------

[OUTPUT]
    Name          loki
    Match         host.* app.* slow.*
    host          \${LOKI_HOST}
    port          \${LOKI_PORT}
    tls           on
    tls.verify    on
    tenant_id     ${LOKI_TENANT}
    labels        job=fluent-bit, host=\$host, environment=\$environment, service=\$service
    label_keys    \$tag,\$level
    line_format   json
    workers       2
    storage.total_limit_size 2G
    Retry_Limit   no_limits

[OUTPUT]
    Name          es
    Match         app.* slow.*
    Host          ${ES_HOST}
    Port          ${ES_PORT}
    HTTP_User     ${ES_USER}
    HTTP_Passwd   ${ES_PASS}
    tls           on
    tls.verify    on
    Index         ${ES_INDEX}
    Logstash_Format On
    Logstash_Prefix ${ES_INDEX}
    Logstash_DateFormat %Y.%m.%d
    Replace_Dots  On
    Suppress_Type_Name On
    Trace_Error   On
    storage.total_limit_size 5G
    Retry_Limit   no_limits

[OUTPUT]
    Name          s3
    Match         *
    bucket        ${S3_BUCKET}
    region        ${S3_REGION}
    total_file_size 50M
    upload_timeout 10m
    s3_key_format /${S3_PREFIX}/${ENVIRONMENT}/${HOSTNAME_TAG}/%Y/%m/%d/%H/\$TAG/%H%M%S-\$UUID.gz
    compression   gzip
    use_put_object Off
    storage.total_limit_size 10G
    Retry_Limit   no_limits
EOF

echo "==> Plugins file (placeholder, kept for future native plugins)"
cat > /etc/fluent-bit/plugins.conf <<'PLUGINS'
PLUGINS

echo "==> Loki host/port env (split URL for the loki output)"
LOKI_HOST="$(echo "${LOKI_URL}" | awk -F[/:] '{print $4}')"
LOKI_PORT="$(echo "${LOKI_URL}" | awk -F[/:] '{print $5}')"
[[ -z "${LOKI_PORT}" || "${LOKI_PORT}" == *[a-z]* ]] && LOKI_PORT=443

mkdir -p /etc/systemd/system/fluent-bit.service.d
cat > /etc/systemd/system/fluent-bit.service.d/override.conf <<EOF
[Service]
Environment=LOKI_HOST=${LOKI_HOST}
Environment=LOKI_PORT=${LOKI_PORT}
Environment=AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID}
Environment=AWS_SECRET_ACCESS_KEY=${AWS_SECRET_ACCESS_KEY}
Environment=AWS_REGION=${S3_REGION}
LimitNOFILE=65535
LimitNPROC=8192
EOF

echo "==> Reloading and starting fluent-bit"
systemctl daemon-reload
systemctl enable --now fluent-bit
sleep 3

echo
echo "========================================"
echo "DONE"
echo "========================================"
echo

echo "Service status:"
systemctl is-active fluent-bit || true
echo

echo "Recent journal lines:"
journalctl -u fluent-bit -n 20 --no-pager || true
echo

echo "Plugin metrics (records flowing):"
sleep 5
curl -s http://127.0.0.1:2020/api/v1/metrics | jq '.input, .output' || true
echo
echo "Storage backlog:"
curl -s http://127.0.0.1:2020/api/v1/storage | jq '.storage_layer' || true
echo
echo "Next: confirm records arriving in Loki/Elasticsearch and the first S3 object lands within 10m."

Make it executable and run once:

chmod 700 /root/setup-fluent-bit.sh
/root/setup-fluent-bit.sh

After it returns, watch curl -s http://127.0.0.1:2020/api/v1/metrics | jq '.output' for sixty seconds. The loki.0, es.0, and s3.0 counters should all show proc_records climbing and errors flat at zero. If errors is non-zero on one output, the other two will keep working — that’s the point of fanning out at the shipper. Don’t repoint at a downstream from the application directly.

For pipelines that fan out further (multi-region Loki, S3 cross-account, kafka in the middle), our monitoring + on-call team operates the shipper tier and the destinations under one environment management contract — scope the rollout with us.