Skip to content

Deploying Grafana Loki + Promtail on Ubuntu 22.04 (production-ready)

Stand up self-hosted Loki single-binary + Promtail on Ubuntu 22.04 — filesystem or S3 chunks, localhost-bound, nginx + Let's Encrypt, retention policy.

You stood up Loki single-binary, pointed Promtail at /var/log, hooked it into Grafana, and the first few queries returned logs. Six months later, /var/lib/loki has eaten 80 % of the root volume because nothing ever expired chunks; queries that span more than 24 hours time out; the API is exposed on 0.0.0.0:3100 from the public NAT; and the engineer who set it up is gone. The dashboards still show the latest hour, so nobody noticed.

What’s happening

Loki is deceptively simple to start and deceptively complex to keep healthy. The single-binary mode is fine for a small fleet, but it needs the right compactor block (otherwise old chunks never get deleted), a real retention policy keyed off the schema config (not just a TTL flag), and an explicit chunk-store backend choice — filesystem for under 100 GB/day, S3-compatible for anything bigger because the local FS won’t survive object count growth. Promtail needs pipeline_stages so labels stay bounded (cardinality explosion is the most common Loki postmortem). The HTTP listener belongs on 127.0.0.1; only nginx with a TLS cert and basic auth should face the internet. None of these are individually exotic. They compound when you skip them.

How to verify

After install, the listeners should bind only to localhost (the public side is nginx):

ss -lntp | grep -E ':(3100|9080|443)\b'
# 127.0.0.1:3100   loki
# 127.0.0.1:9080   promtail
# 0.0.0.0:443      nginx

Loki’s own readiness probe confirms ingest is healthy:

curl -s http://127.0.0.1:3100/ready
# ready

A quick label query confirms Promtail is actually shipping:

curl -s 'http://127.0.0.1:3100/loki/api/v1/labels' \
  | python3 -m json.tool

If 3100 shows 0.0.0.0, the perimeter is open. If /ready returns Ingester not ready, the WAL is still replaying — wait, then look at logs.

The fix

Save the script below as /root/setup-loki-ubuntu2204.sh, then run it. It performs the full installer flow on a fresh Ubuntu 22.04 VM: base update, UFW, SSH hardening (root key login kept, password disabled), unattended-upgrades for security, dedicated loki and promtail system users, the official binaries pinned to a current 3.x line, single-binary mode with the tsdb index and filesystem chunks (with an S3 stanza you flip on by setting env vars), compactor enabled with retention, Promtail tailing systemd journal plus /var/log/*.log with sensible pipeline stages, nginx + certbot for the external UI, basic auth on the public path, and LimitNOFILE=64000. The script waits for each listener before continuing.

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

### Ubuntu 22.04 Loki + Promtail clean VM installer
### Single-binary Loki 3.x with tsdb index, filesystem chunks by default
### Set LOKI_S3_* env vars to flip to S3-compatible storage
### All daemons bind to 127.0.0.1; only nginx is public
### TLS via Let's Encrypt; basic-auth on /loki and /promtail
### Keeps root SSH key login; disables password auth
### No local backups; assumes VM-level backup

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

: "${LOKI_DOMAIN:?Set LOKI_DOMAIN, e.g. logs.example.com}"
: "${LOKI_EMAIL:?Set LOKI_EMAIL for Let's Encrypt}"
: "${LOKI_BASIC_USER:?Set LOKI_BASIC_USER}"
: "${LOKI_BASIC_PASS:?Set LOKI_BASIC_PASS}"

LOKI_VERSION="3.1.1"

# Optional S3-compatible backend:
LOKI_S3_BUCKET="${LOKI_S3_BUCKET:-}"
LOKI_S3_REGION="${LOKI_S3_REGION:-}"
LOKI_S3_ENDPOINT="${LOKI_S3_ENDPOINT:-}"
LOKI_S3_ACCESS_KEY="${LOKI_S3_ACCESS_KEY:-}"
LOKI_S3_SECRET_KEY="${LOKI_S3_SECRET_KEY:-}"

echo
echo "========================================"
echo "Loki + Promtail Ubuntu 22.04 Setup"
echo "Domain: $LOKI_DOMAIN"
echo "========================================"
echo

export DEBIAN_FRONTEND=noninteractive

echo "==> Updating base OS"
apt-get update
apt-get -y upgrade

echo "==> Installing base packages"
apt-get -y install \
  curl wget unzip ca-certificates gnupg \
  chrony fail2ban unattended-upgrades \
  lsof tcpdump dnsutils iproute2 net-tools jq \
  nginx apache2-utils \
  ufw

systemctl enable --now chronyd 2>/dev/null || systemctl enable --now chrony

echo "==> sysctl + file limits"
cat > /etc/sysctl.d/99-observability.conf <<'SYSCTL'
net.core.somaxconn = 4096
net.core.netdev_max_backlog = 250000
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_syncookies = 1
fs.file-max = 2097152
kernel.dmesg_restrict = 1
SYSCTL
sysctl --system

cat > /etc/security/limits.d/99-observability.conf <<'LIMITS'
* soft nofile 64000
* hard nofile 64000
LIMITS

echo "==> Hardening SSH (keep root key)"
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak.$(date +%F-%H%M%S)
set_sshd() {
  local k="$1" v="$2"
  if grep -qE "^[#[:space:]]*${k}[[:space:]]+" /etc/ssh/sshd_config; then
    sed -i "s|^[#[:space:]]*${k}[[:space:]].*|${k} ${v}|" /etc/ssh/sshd_config
  else
    echo "${k} ${v}" >> /etc/ssh/sshd_config
  fi
}
set_sshd PermitRootLogin prohibit-password
set_sshd PasswordAuthentication no
set_sshd PubkeyAuthentication yes
set_sshd KbdInteractiveAuthentication no
set_sshd X11Forwarding no
set_sshd ClientAliveInterval 300
set_sshd MaxAuthTries 4
sshd -t
systemctl restart ssh

echo "==> fail2ban + unattended-upgrades"
cat > /etc/fail2ban/jail.d/sshd.local <<'F2B'
[sshd]
enabled = true
port = ssh
backend = systemd
maxretry = 4
findtime = 10m
bantime = 1h
F2B
systemctl enable --now fail2ban

cat > /etc/apt/apt.conf.d/20auto-upgrades <<'AUTO'
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
AUTO
systemctl enable --now unattended-upgrades

echo "==> UFW: 22, 80, 443 only"
ufw --force reset
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp
ufw allow 80/tcp
ufw allow 443/tcp
ufw --force enable

echo "==> Creating system users"
id -u loki     >/dev/null 2>&1 || useradd -rs /usr/sbin/nologin loki
id -u promtail >/dev/null 2>&1 || useradd -rs /usr/sbin/nologin promtail
# Promtail reads journald + /var/log; add to adm + systemd-journal
usermod -a -G adm,systemd-journal promtail

echo "==> Installing Loki ${LOKI_VERSION}"
cd /tmp
curl -fsSLO "https://github.com/grafana/loki/releases/download/v${LOKI_VERSION}/loki-linux-amd64.zip"
unzip -o loki-linux-amd64.zip
install -m 0755 loki-linux-amd64 /usr/local/bin/loki

curl -fsSLO "https://github.com/grafana/loki/releases/download/v${LOKI_VERSION}/promtail-linux-amd64.zip"
unzip -o promtail-linux-amd64.zip
install -m 0755 promtail-linux-amd64 /usr/local/bin/promtail

mkdir -p /etc/loki /var/lib/loki/{chunks,boltdb-shipper-active,boltdb-shipper-cache,wal,compactor,tsdb-index,tsdb-cache}
chown -R loki:loki /etc/loki /var/lib/loki

echo "==> Writing loki-config.yaml"
if [[ -n "$LOKI_S3_BUCKET" ]]; then
  echo "  (using S3-compatible chunks at ${LOKI_S3_ENDPOINT:-s3.amazonaws.com}/${LOKI_S3_BUCKET})"
  STORAGE_BLOCK=$(cat <<S3YAML
  aws:
    s3: s3://${LOKI_S3_ACCESS_KEY}:${LOKI_S3_SECRET_KEY}@${LOKI_S3_REGION}/${LOKI_S3_BUCKET}
    s3forcepathstyle: true
    endpoint: ${LOKI_S3_ENDPOINT}
S3YAML
)
  CHUNK_STORE='aws'
else
  echo "  (using filesystem chunks at /var/lib/loki/chunks)"
  STORAGE_BLOCK=$(cat <<'FSYAML'
  filesystem:
    directory: /var/lib/loki/chunks
FSYAML
)
  CHUNK_STORE='filesystem'
fi

cat > /etc/loki/loki-config.yaml <<LOKIYAML
auth_enabled: false

server:
  http_listen_address: 127.0.0.1
  http_listen_port: 3100
  grpc_listen_address: 127.0.0.1
  grpc_listen_port: 9095
  log_level: info

common:
  instance_addr: 127.0.0.1
  path_prefix: /var/lib/loki
  replication_factor: 1
  ring:
    kvstore:
      store: inmemory

ingester:
  wal:
    enabled: true
    dir: /var/lib/loki/wal
  lifecycler:
    address: 127.0.0.1
  chunk_idle_period: 30m
  chunk_target_size: 1572864
  max_chunk_age: 2h

schema_config:
  configs:
    - from: 2024-01-01
      store: tsdb
      object_store: ${CHUNK_STORE}
      schema: v13
      index:
        prefix: loki_index_
        period: 24h

storage_config:
${STORAGE_BLOCK}
  tsdb_shipper:
    active_index_directory: /var/lib/loki/tsdb-index
    cache_location: /var/lib/loki/tsdb-cache

compactor:
  working_directory: /var/lib/loki/compactor
  compaction_interval: 10m
  retention_enabled: true
  retention_delete_delay: 2h
  retention_delete_worker_count: 150
  delete_request_store: ${CHUNK_STORE}

limits_config:
  retention_period: 720h           # 30 days
  ingestion_rate_mb: 8
  ingestion_burst_size_mb: 16
  max_query_series: 5000
  max_streams_per_user: 0
  reject_old_samples: true
  reject_old_samples_max_age: 168h

ruler:
  storage:
    type: local
    local:
      directory: /etc/loki/rules
  rule_path: /var/lib/loki/rules-temp
  ring:
    kvstore:
      store: inmemory
  enable_api: true

analytics:
  reporting_enabled: false
LOKIYAML

mkdir -p /etc/loki/rules
chown -R loki:loki /etc/loki

cat > /etc/systemd/system/loki.service <<'LOKIUNIT'
[Unit]
Description=Loki
After=network-online.target
Wants=network-online.target

[Service]
User=loki
Group=loki
Type=simple
LimitNOFILE=64000
ExecStart=/usr/local/bin/loki -config.file=/etc/loki/loki-config.yaml
Restart=on-failure
RestartSec=5s

[Install]
WantedBy=multi-user.target
LOKIUNIT

echo "==> Writing promtail-config.yaml"
mkdir -p /etc/promtail /var/lib/promtail
chown -R promtail:promtail /etc/promtail /var/lib/promtail

cat > /etc/promtail/promtail-config.yaml <<'PROMTAIL'
server:
  http_listen_address: 127.0.0.1
  http_listen_port: 9080
  grpc_listen_address: 127.0.0.1
  grpc_listen_port: 9096

positions:
  filename: /var/lib/promtail/positions.yaml

clients:
  - url: http://127.0.0.1:3100/loki/api/v1/push
    batchwait: 1s
    batchsize: 1048576

scrape_configs:
  - job_name: journal
    journal:
      max_age: 12h
      labels:
        job: systemd-journal
        host: ${HOSTNAME}
    relabel_configs:
      - source_labels: ['__journal__systemd_unit']
        target_label: 'unit'
      - source_labels: ['__journal_priority_keyword']
        target_label: 'priority'

  - job_name: varlogs
    static_configs:
      - targets: [localhost]
        labels:
          job: varlogs
          host: ${HOSTNAME}
          __path__: /var/log/*.log
    pipeline_stages:
      - match:
          selector: '{job="varlogs"}'
          stages:
            - regex:
                expression: '^(?P<timestamp>\S+ \S+) (?P<level>\w+)'
            - labels:
                level:
PROMTAIL

cat > /etc/systemd/system/promtail.service <<'PTUNIT'
[Unit]
Description=Promtail
After=network-online.target loki.service
Wants=network-online.target

[Service]
User=promtail
Group=promtail
Type=simple
LimitNOFILE=64000
ExecStart=/usr/local/bin/promtail -config.file=/etc/promtail/promtail-config.yaml -config.expand-env=true
Restart=on-failure
RestartSec=5s

[Install]
WantedBy=multi-user.target
PTUNIT

systemctl daemon-reload

echo "==> Starting Loki + Promtail"
systemctl enable --now loki
sleep 3
systemctl enable --now promtail

echo "==> Waiting for Loki readiness"
for i in {1..60}; do
  if curl -fsS http://127.0.0.1:3100/ready >/dev/null 2>&1; then
    echo "  loki ready"
    break
  fi
  sleep 2
done

echo "==> Waiting for Promtail listener"
for i in {1..30}; do
  if ss -lntp | grep -q '127.0.0.1:9080'; then
    echo "  promtail up"
    break
  fi
  sleep 1
done

echo "==> nginx + Let's Encrypt + basic auth"
htpasswd -bc /etc/nginx/loki.htpasswd "$LOKI_BASIC_USER" "$LOKI_BASIC_PASS"
chmod 640 /etc/nginx/loki.htpasswd
chown root:www-data /etc/nginx/loki.htpasswd

apt-get -y install certbot python3-certbot-nginx

cat > /etc/nginx/sites-available/loki <<NGINX_BOOT
server {
    listen 80;
    server_name ${LOKI_DOMAIN};
    location /.well-known/acme-challenge/ { root /var/www/html; }
    location / { return 200 'bootstrap'; }
}
NGINX_BOOT
ln -sf /etc/nginx/sites-available/loki /etc/nginx/sites-enabled/loki
rm -f /etc/nginx/sites-enabled/default
mkdir -p /var/www/html
nginx -t && systemctl reload nginx

if [[ ! -d /etc/letsencrypt/live/${LOKI_DOMAIN} ]]; then
  certbot certonly --webroot -w /var/www/html \
    -d "${LOKI_DOMAIN}" -m "${LOKI_EMAIL}" --agree-tos --non-interactive
fi

cat > /etc/nginx/sites-available/loki <<NGINX
server {
    listen 80;
    server_name ${LOKI_DOMAIN};
    location /.well-known/acme-challenge/ { root /var/www/html; }
    location / { return 301 https://\$host\$request_uri; }
}

server {
    listen 443 ssl http2;
    server_name ${LOKI_DOMAIN};

    ssl_certificate /etc/letsencrypt/live/${LOKI_DOMAIN}/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/${LOKI_DOMAIN}/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    add_header Strict-Transport-Security "max-age=31536000" always;

    auth_basic "loki";
    auth_basic_user_file /etc/nginx/loki.htpasswd;

    client_max_body_size 100M;

    location / {
        proxy_pass http://127.0.0.1:3100/;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-Proto https;
        proxy_read_timeout 300s;
    }
}
NGINX

nginx -t && systemctl reload nginx
systemctl enable --now certbot.timer 2>/dev/null || true

echo "==> Final apt upgrade"
apt-get -y upgrade

echo
echo "========================================"
echo "DONE"
echo "========================================"
echo
echo "Listeners:"
ss -lntp | grep -E ':(3100|9080|443|80)\b' || true
echo
echo "Services:"
systemctl is-active loki promtail nginx fail2ban || true
echo
echo "Loki ready:"
curl -s http://127.0.0.1:3100/ready
echo
echo "Loki labels (Promtail should be pushing):"
curl -s http://127.0.0.1:3100/loki/api/v1/labels | head -c 500 || true
echo
echo "Public Loki URL: https://${LOKI_DOMAIN}/  (basic auth: ${LOKI_BASIC_USER})"
echo
echo "Final step:"
echo "  In Grafana, add data source:"
echo "    URL:  https://${LOKI_DOMAIN}/"
echo "    Auth: basic, ${LOKI_BASIC_USER} / <set>"

Make it executable and run it:

chmod 700 /root/setup-loki-ubuntu2204.sh
LOKI_DOMAIN=logs.example.com LOKI_EMAIL=ops@example.com \
  LOKI_BASIC_USER=ingest LOKI_BASIC_PASS='set-a-real-one' \
  /root/setup-loki-ubuntu2204.sh

The script prints listener summary, /ready state, and the active labels at the end. By default chunks live on the local filesystem under /var/lib/loki/chunks — fine up to roughly 100 GB/day of ingest. For anything bigger or with cross-host durability needs, re-run with LOKI_S3_BUCKET, LOKI_S3_REGION, LOKI_S3_ENDPOINT, LOKI_S3_ACCESS_KEY, LOKI_S3_SECRET_KEY set and the schema flips to S3-compatible storage. Retention is 30 days via limits_config.retention_period; the compactor enforces it asynchronously, so disk doesn’t free instantly after a config change.

Stack Harbor runs Loki at production scale — sized retention, label hygiene, query-side rate limits — as part of environment management. If your log stack is louder than it is useful, book a review.