Skip to content

Deploying Longhorn block storage on k3s + Ubuntu 22.04

Install Longhorn on a three-node k3s cluster running Ubuntu 22.04 — replica scheduling, snapshot schedules, backup target, and the operational guardrails that keep it from eating itself.

You bring up a three-node k3s cluster for a small team that wants to self-host a handful of stateful services — a Postgres, a Redis, a Gitea, a few app containers that all expect ReadWriteOnce persistent volumes. The first pod with a PVC schedules, and nothing happens for ten minutes — the PVC is Pending, the events say no persistent volumes available for this claim, and somebody on the team types kubectl get sc and stares at an empty list. k3s by default ships only the local-path provisioner, which writes to the node’s filesystem with zero replication. A node reboot doesn’t lose the data, but a node failure loses it permanently, and the pod can’t reschedule anywhere else because the volume only lives on one disk. The cluster needs a real distributed block storage layer with replication across nodes, snapshots, and an off-cluster backup target. Longhorn does that, and unlike Ceph it doesn’t require a dedicated storage team to operate.

What’s happening

Longhorn is a Kubernetes-native distributed block storage system. Each Persistent Volume gets a Longhorn Volume resource that is materialized as a set of replicas — typically three — scheduled across different nodes. The replicas talk to each other over the cluster network using a Longhorn-internal protocol; the read/write path goes through a per-volume “engine” pod that the workload pod connects to via iSCSI. From the application’s point of view, it’s just a block device mounted by the kubelet. From Longhorn’s point of view, every replica is a separate sparse file on a different node’s /var/lib/longhorn directory, and the engine reconciles writes to all healthy replicas synchronously. Snapshots are cheap copy-on-write deltas on top of the volume. Backups are full materializations of a snapshot pushed to an S3-compatible target, and the backup chain is what protects you when a cluster-wide event takes out all three replicas at once.

The two failure modes most operators hit are: replica scheduling that quietly stops working because of disk pressure or anti-affinity violations (Longhorn marks the volume Degraded and waits, but does not page anyone), and backup targets that drift into “configured but unreachable” because of S3 credential rotation. Both are silent. Both can be alerted on via the Longhorn manager API.

How to verify

Storage class is real and is the default:

kubectl get sc
# NAME                 PROVISIONER          RECLAIMPOLICY   ...   IsDefault
# longhorn (default)   driver.longhorn.io   Delete                true

Longhorn manager pods are healthy on every node and CSI plugins are deployed:

kubectl -n longhorn-system get pods -o wide | head -30
# longhorn-manager-xxxxx   1/1   Running   ...   k3s-01
# longhorn-manager-xxxxx   1/1   Running   ...   k3s-02
# longhorn-manager-xxxxx   1/1   Running   ...   k3s-03
# longhorn-driver-deployer-xxxxx   1/1   Running   ...
# csi-attacher-xxxxx               1/1   Running   ...
# csi-provisioner-xxxxx            1/1   Running   ...

Volume health from inside the cluster — what your monitoring should actually alert on:

kubectl -n longhorn-system get volumes.longhorn.io \
  -o custom-columns=NAME:.metadata.name,STATE:.status.state,ROBUSTNESS:.status.robustness,SIZE:.spec.size
# pvc-aaaa  attached  healthy    21474836480
# pvc-bbbb  attached  healthy    10737418240
# pvc-cccc  attached  degraded   53687091200    <-- this is the alert

degraded means fewer healthy replicas than the spec requested — usually a node went down, sometimes a disk filled up. Backup target reachability:

kubectl -n longhorn-system get backuptargets.longhorn.io default \
  -o jsonpath='{.status.available}{"\n"}'
# true

If this returns false or empty, your “we have backups” story is a fiction until you fix it.

The fix

Save the script as /root/setup-longhorn.sh and run it once on the first k3s node (the one running the k3s server). The other two nodes need only the base prep block at the top — copy/paste those lines on the agents before the manager pod tries to schedule there.

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

### Ubuntu 22.04 + k3s + Longhorn block storage installer
### Run the BASE PREP on all 3 nodes (server + 2 agents)
### Run the K3S SERVER + HELM + LONGHORN block on the server node only
### Assumes a separate /dev/sdb disk on each node for /var/lib/longhorn

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

# === EDIT PER DEPLOYMENT ===
NODE_ROLE="server"            # server on the first node; agent on the others
K3S_SERVER_IP="10.30.0.11"    # IP of the k3s server (use the same value on agents)
K3S_TOKEN="CHANGE_ME_K3S_TOKEN"
LONGHORN_VERSION="v1.7.2"
LONGHORN_DATA_DISK="/dev/sdb"
S3_ENDPOINT="https://s3.example.com"
S3_BUCKET="longhorn-backups"
S3_REGION="us-east-1"
S3_ACCESS_KEY="CHANGE_ME_S3_AK"
S3_SECRET_KEY="CHANGE_ME_S3_SK"
DEFAULT_REPLICA_COUNT=3
BACKUP_SCHEDULE_CRON="0 2 * * *"   # nightly 02:00 UTC
SNAPSHOT_SCHEDULE_CRON="0 */6 * * *"
SNAPSHOT_RETAIN=8
BACKUP_RETAIN=14
# ===========================

echo
echo "========================================"
echo "BASE PREP (run on every node)"
echo "========================================"
echo

export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get -y install curl wget jq lsof tcpdump iproute2 chrony ufw \
  unattended-upgrades open-iscsi nfs-common util-linux \
  e2fsprogs xfsprogs parted bash-completion

systemctl enable --now chrony

echo "==> open-iscsi is required by Longhorn for the engine attach path"
systemctl enable --now iscsid

echo "==> Multipath blacklist for Longhorn devices (Longhorn does NOT play well with multipathd)"
mkdir -p /etc/multipath/conf.d
cat > /etc/multipath/conf.d/blacklist-longhorn.conf <<'MPATH'
blacklist {
    devnode "^sd[a-z0-9]+"
}
MPATH

systemctl is-enabled multipathd 2>/dev/null && systemctl restart multipathd || true

echo "==> Kernel modules required by Longhorn"
cat > /etc/modules-load.d/longhorn.conf <<'MODS'
iscsi_tcp
nfs
MODS
modprobe iscsi_tcp || true
modprobe nfs || true

echo "==> Preparing the dedicated data disk: ${LONGHORN_DATA_DISK}"
if [[ -b "${LONGHORN_DATA_DISK}" ]]; then
  if ! blkid "${LONGHORN_DATA_DISK}" >/dev/null 2>&1; then
    mkfs.ext4 -L longhorn -F "${LONGHORN_DATA_DISK}"
  fi
  mkdir -p /var/lib/longhorn
  if ! grep -q "/var/lib/longhorn" /etc/fstab; then
    echo "${LONGHORN_DATA_DISK} /var/lib/longhorn ext4 defaults,noatime,nodiratime 0 2" >> /etc/fstab
  fi
  mount /var/lib/longhorn || true
else
  echo "WARN: ${LONGHORN_DATA_DISK} not present; Longhorn will use the root disk under /var/lib/longhorn"
  mkdir -p /var/lib/longhorn
fi

echo "==> Firewall — allow Longhorn pod traffic between nodes"
ufw --force reset
ufw default deny incoming
ufw default allow outgoing
ufw allow OpenSSH
# k3s + flannel + Longhorn
ufw allow from 10.30.0.0/24 to any port 6443 proto tcp comment 'k3s API'
ufw allow from 10.42.0.0/16 to any comment 'flannel pod network'
ufw allow from 10.30.0.0/24 to any port 10250 proto tcp comment 'kubelet'
ufw allow from 10.30.0.0/24 to any port 8500:8501 proto tcp comment 'Longhorn manager'
ufw allow from 10.30.0.0/24 to any port 3260 proto tcp comment 'iSCSI'
ufw allow from 10.30.0.0/24 to any port 4789 proto udp comment 'flannel vxlan'
ufw --force enable

echo "==> Sysctl — engine container ulimits"
cat > /etc/sysctl.d/99-longhorn.conf <<'SYSCTL'
fs.inotify.max_user_watches = 1048576
fs.inotify.max_user_instances = 8192
SYSCTL
sysctl --system

if [[ "${NODE_ROLE}" == "agent" ]]; then
  echo
  echo "==> Installing k3s agent against ${K3S_SERVER_IP}"
  curl -sfL https://get.k3s.io | \
    K3S_URL="https://${K3S_SERVER_IP}:6443" \
    K3S_TOKEN="${K3S_TOKEN}" \
    sh -s - agent

  echo "==> Agent install complete. The rest of the script runs on the server node only."
  exit 0
fi

echo
echo "========================================"
echo "K3S SERVER + HELM + LONGHORN"
echo "========================================"
echo

echo "==> Installing k3s server (disable traefik; Longhorn doesn't need it)"
curl -sfL https://get.k3s.io | \
  INSTALL_K3S_EXEC="server --disable=traefik --write-kubeconfig-mode=600 --token=${K3S_TOKEN} --node-ip=${K3S_SERVER_IP} --advertise-address=${K3S_SERVER_IP} --cluster-init" \
  sh -

export KUBECONFIG=/etc/rancher/k3s/k3s.yaml
mkdir -p /root/.kube
cp /etc/rancher/k3s/k3s.yaml /root/.kube/config

echo "==> Waiting for the k3s server node to register"
for i in {1..60}; do
  if kubectl get nodes >/dev/null 2>&1; then break; fi
  sleep 2
done

echo
echo "==> NODE TOKEN FOR AGENTS:"
cat /var/lib/rancher/k3s/server/node-token
echo "Use the printed token as K3S_TOKEN on the agent nodes."
echo

echo "==> Installing Helm"
curl -fsSL https://baltocdn.com/helm/signing.asc | gpg --dearmor -o /usr/share/keyrings/helm.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/helm.gpg] https://baltocdn.com/helm/stable/debian/ all main" \
  > /etc/apt/sources.list.d/helm-stable-debian.list
apt-get update
apt-get -y install helm

echo "==> Adding longhorn helm repo"
helm repo add longhorn https://charts.longhorn.io
helm repo update

echo "==> Creating longhorn-system namespace"
kubectl create namespace longhorn-system --dry-run=client -o yaml | kubectl apply -f -

echo "==> Creating S3 backup-target secret"
kubectl -n longhorn-system create secret generic longhorn-backup-s3 \
  --from-literal=AWS_ACCESS_KEY_ID="${S3_ACCESS_KEY}" \
  --from-literal=AWS_SECRET_ACCESS_KEY="${S3_SECRET_KEY}" \
  --from-literal=AWS_ENDPOINTS="${S3_ENDPOINT}" \
  --from-literal=AWS_REGION="${S3_REGION}" \
  --dry-run=client -o yaml | kubectl apply -f -

echo "==> Installing Longhorn ${LONGHORN_VERSION}"
cat > /root/longhorn-values.yaml <<EOF
persistence:
  defaultClass: true
  defaultClassReplicaCount: ${DEFAULT_REPLICA_COUNT}
  defaultFsType: ext4
  defaultDataLocality: best-effort
  reclaimPolicy: Delete

defaultSettings:
  defaultDataPath: /var/lib/longhorn
  defaultReplicaCount: ${DEFAULT_REPLICA_COUNT}
  defaultDataLocality: best-effort
  replicaSoftAntiAffinity: false
  replicaAutoBalance: best-effort
  storageOverProvisioningPercentage: 100
  storageMinimalAvailablePercentage: 15
  upgradeChecker: false
  backupTarget: s3://${S3_BUCKET}@${S3_REGION}/
  backupTargetCredentialSecret: longhorn-backup-s3
  allowVolumeCreationWithDegradedAvailability: false
  autoCleanupSystemGeneratedSnapshot: true
  autoSalvage: true
  disableSchedulingOnCordonedNode: true
  guaranteedInstanceManagerCPU: 12
  recurringJobMaxRetention: 50
  snapshotDataIntegrity: fast-check
  snapshotDataIntegrityCronJob: "0 4 * * 0"
  backupCompressionMethod: lz4
  concurrentReplicaRebuildPerNodeLimit: 5
  concurrentBackupRestorePerNodeLimit: 5
  failedBackupTTL: 1440
  restoreVolumeRecurringJobs: true
  systemManagedComponentsNodeSelector: ""

longhornManager:
  log:
    format: json

longhornUI:
  replicas: 2

ingress:
  enabled: false
EOF

helm upgrade --install longhorn longhorn/longhorn \
  --namespace longhorn-system \
  --version "${LONGHORN_VERSION}" \
  -f /root/longhorn-values.yaml

echo "==> Waiting for Longhorn manager pods to become Ready"
kubectl -n longhorn-system rollout status daemonset/longhorn-manager --timeout=300s

echo "==> Creating a RecurringJob for snapshots + backups (cluster-wide default)"
cat > /tmp/longhorn-recurring.yaml <<EOF
apiVersion: longhorn.io/v1beta2
kind: RecurringJob
metadata:
  name: snapshot-6h
  namespace: longhorn-system
spec:
  cron: "${SNAPSHOT_SCHEDULE_CRON}"
  task: snapshot
  groups:
    - default
  retain: ${SNAPSHOT_RETAIN}
  concurrency: 4
  labels:
    schedule: snapshot-6h
---
apiVersion: longhorn.io/v1beta2
kind: RecurringJob
metadata:
  name: backup-nightly
  namespace: longhorn-system
spec:
  cron: "${BACKUP_SCHEDULE_CRON}"
  task: backup
  groups:
    - default
  retain: ${BACKUP_RETAIN}
  concurrency: 2
  labels:
    schedule: backup-nightly
EOF

kubectl apply -f /tmp/longhorn-recurring.yaml

echo "==> Patch the longhorn StorageClass to attach the 'default' RecurringJob group automatically"
kubectl patch storageclass longhorn -p '{"parameters":{"recurringJobSelector":"[{\"name\":\"snapshot-6h\",\"isGroup\":false},{\"name\":\"backup-nightly\",\"isGroup\":false}]"}}'

echo
echo "==> Smoke test: provisioning a 1Gi PVC and writing into it"
cat > /tmp/longhorn-smoke.yaml <<EOF
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: smoke-pvc
  namespace: default
spec:
  accessModes: [ReadWriteOnce]
  storageClassName: longhorn
  resources:
    requests:
      storage: 1Gi
---
apiVersion: v1
kind: Pod
metadata:
  name: smoke-writer
  namespace: default
spec:
  restartPolicy: Never
  containers:
    - name: w
      image: busybox:1.36
      command: ["sh","-c","dd if=/dev/zero of=/data/test bs=1M count=128 && sync && ls -lh /data && sleep 5"]
      volumeMounts:
        - name: data
          mountPath: /data
  volumes:
    - name: data
      persistentVolumeClaim:
        claimName: smoke-pvc
EOF
kubectl apply -f /tmp/longhorn-smoke.yaml

echo "==> Waiting for smoke pod to complete"
kubectl wait --for=condition=Ready pod/smoke-writer -n default --timeout=120s || true
sleep 10
kubectl logs smoke-writer -n default || true

echo "==> Inspecting the resulting Longhorn volume"
kubectl -n longhorn-system get volumes.longhorn.io

echo
echo "========================================"
echo "DONE"
echo "========================================"
echo
echo "Longhorn UI (port-forward only — do not expose unauthenticated):"
echo "  kubectl -n longhorn-system port-forward svc/longhorn-frontend 8080:80"
echo
echo "Backup target status:"
echo "  kubectl -n longhorn-system get backuptargets.longhorn.io default -o yaml | grep -E 'available|message'"
echo
echo "Repeat the BASE PREP block on the two agent nodes, then run k3s agent install:"
echo "  curl -sfL https://get.k3s.io | K3S_URL=https://${K3S_SERVER_IP}:6443 K3S_TOKEN=<token> sh -s - agent"

Make it executable and run on the server node:

chmod 700 /root/setup-longhorn.sh
/root/setup-longhorn.sh

A few production guardrails Longhorn does not enforce for you:

  1. Replica count of 3 only protects you against single-node failure. If you run on a two-node cluster, you have one effective copy plus an engine — that is not HA. Three nodes is the floor.
  2. Disk pressure breaks scheduling silently. The storageMinimalAvailablePercentage parameter (15% in the script) is what prevents Longhorn from filling a node to the brim and then refusing to schedule new replicas. Watch the node.longhorn.io objects for disk pressure conditions and alert on them.
  3. Backup target is the only thing that survives a full cluster loss. A snapshot is a delta on the same volume; if the cluster’s disks are gone, the snapshot is gone too. The S3 bucket is your real restore-from-zero asset, and the credentials in longhorn-backup-s3 need to be the only thing scoped to write into that bucket — rotate them on a schedule and re-test the restore path.
  4. Don’t put Longhorn on the root disk in production. The script provisions /dev/sdb as a dedicated data disk. If you skip that step, a runaway log file on the root filesystem can starve the engine, and Longhorn detects “disk pressure” as “the node is sick” — replicas leave, the cluster rebuilds, and you’ve spent two hours rebalancing for no reason.

Restore drill template — run this quarterly:

# 1. Find a recent backup
kubectl -n longhorn-system get backups.longhorn.io
# 2. Create a new volume from that backup
kubectl apply -f - <<EOF
apiVersion: longhorn.io/v1beta2
kind: Volume
metadata:
  name: restore-drill-$(date +%Y%m%d)
  namespace: longhorn-system
spec:
  numberOfReplicas: 3
  size: "21474836480"
  fromBackup: "s3://${S3_BUCKET}@${S3_REGION}/?backup=<backup-id>&volume=<source-volume>"
EOF
# 3. Attach, mount in a debug pod, diff against expected contents

A backup that is never restored is a hypothesis, not a backup.

Stack Harbor runs Longhorn-backed k3s clusters under Managed Cloud Ops with the backup target wired into our monitoring plane and quarterly restore drills on the cadence — start a scoping call if you’d like the operational layer without the on-call rotation.