Skip to content

Checking your reading list…

Retry verification

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Kubernetes Storage Deep Dive: PV/PVC/StorageClass with Ceph RBD Integration
Cloud Native 64 min read

Kubernetes Storage Deep Dive: PV/PVC/StorageClass with Ceph RBD Integration

A comprehensive guide to Kubernetes storage architecture with Ceph RBD, covering PV/PVC/StorageClass contracts, CSI sidecar roles, RBD constraints, version compatibility, production baselines, troubleshooting commands, and three real-world failure case studies with root-cause analysis and rollback procedures.

1. Three-Layer Abstraction and Two Data Paths

The article opens by clarifying that PV, PVC, and StorageClass are three distinct contracts belonging to different roles, not layers of the same abstraction. They connect via a one-to-one, essentially irreversible binding.

StorageClass describes capabilities and policies (provisioner, pool, fstype, expansion, binding mode, reclaim policy). Cluster-scoped, reusable, consumes no storage.

PVC describes demand (capacity, accessModes, storageClassName). Namespace-scoped, ephemeral, follows the workload.

PV describes the concrete reality (Ceph image, capacity, volumeHandle, reclaimPolicy). Cluster-scoped, lifecycle independent of namespaces.

Binding is one-to-one. To force a PVC to bind a specific existing PV, use volumeName (pre-binding) with storageClassName: "". Mixing static PVs with dynamic StorageClasses causes expansion failures because the manually created PV lacks CSI fields required by the resizer.

2. Control Plane: Five Sidecars, Each a Potential Failure Point

CSI is just a gRPC interface; Kubernetes translates desired state into CSI RPCs via sidecar containers. A break in any link stalls the PVC at a specific stage.

external-provisioner — Watches PVC, calls CreateVolume. Failure symptom: PVC Pending, no PV created.

external-attacher — Calls ControllerPublishVolume. Failure symptom: Pod stuck in ContainerCreating.

external-resizer — Calls ControllerExpandVolume. Failure symptom: PVC expansion no effect.

external-snapshotter — Calls CreateSnapshot. Failure symptom: VolumeSnapshot Pending.

node-driver-registrar — Registers driver with kubelet. Failure symptom: Driver not found on node.

Provisioner and attacher are cluster-level singletons using --leader-election. Only the leader works; logs show attempting to acquire leader lease vs successfully acquired lease. Identify the leader before debugging.

3. Data Plane: Two Mounts, Five Stages

Data path involves two mounts: a global mount (NodeStageVolume) shared by all pods on the node using the same RBD, then a bind mount (NodePublishVolume) into each pod.

Container /data
  | (3) bind mount  NodePublishVolume
  v
/var/lib/kubelet/pods/<uid>/volumes/kubernetes.io~csi/<pv>/mount
  | (2) bind mount  NodeStageVolume global mount
  v
/var/lib/kubelet/plugins/kubernetes.io/csi/rbd.csi.ceph.com/<hash>/globalmount
  | (1) mkfs.xfs + mount
  v
/dev/rbd3  rbd map (krbd kernel module)
  | (0) Network & object layer
  v
RBD image 4MiB object -> 3 replicas -> 6 OSDs -> 10GbE

Five stages with distinct failure symptoms:

Stage 0 Create Volume — CSI RPC: CreateVolume — Failure: PVC Pending

Stage 1 Map Device — CSI RPC: NodeStageVolume — Failure: rbd: map failed

Stage 2 Format & Mount — CSI RPC: mkfs + mount — Failure: wrong fs type

Stage 3 Mount to Pod — CSI RPC: NodePublishVolume — Failure: no such file

Stage 4 Report Capacity — CSI RPC: kubelet stats — Failure: df numbers wrong

Same-node multi-pod RWO works (shared globalmount); cross-node triggers Multi-Attach because RBD exclusive-lock allows only one writer.

4. RBD Hard Constraints

Single writer : exclusive-lock prevents concurrent writes across nodes. Disabling it causes silent data corruption. For multi-node RWX, use CephFS ( cephfs.csi.ceph.com).

Filesystem fixed at creation : csi.storage.k8s.io/fstype determines mkfs; changing later yields wrong fs type, bad option, bad superblock. Requires new volume + data migration.

Capacity is declared, not actual usage : RBD is thin-provisioned. kubectl get pvc shows 100Gi, rbd du may show 3Gi. Writing beyond declared capacity returns No space left on device even if pool has free space. Monitor pool %USED via ceph df detail, not PVC sum.

Object size (default 4MiB) affects small I/O lock contention; adjustable only at pool creation.

5. Version Baselines

Kubernetes : Article baseline v1.34, minimum viable v1.31. Breaking change: v1.31 removes in-tree rbd.

ceph-csi : Article baseline v3.18.2, minimum viable v3.17.x. Breaking change: v3.19 removes Helm chart.

Ceph : Article baseline Tentacle 20.2.3, minimum viable Squid 19.2.5. Breaking change: 20.2.0 CephFS data loss with readAffinity.

Container Runtime : Article baseline containerd 2.0, minimum viable 1.7. No breaking change.

Version skew often manifests as csi-config-map format mismatches (old array vs new ConfigMap shards) yielding opaque "cluster ID not found" errors.

6. Production Baseline: Nodes, Kernel, Ceph Pool

Baseline cluster: 3 worker nodes (32C/128G), 10GbE storage network (MTU 9000), 3 Ceph nodes each with 8×3.84TB NVMe (24 OSDs total), Ceph Tentacle 20.2.3.

PG Calculation : Target 100-200 PGs per OSD. For 24 OSDs, replication 3: pg_num = (24*100)/3 = 800 to (24*200)/3 = 1600. Choose power of two: 1024. Each OSD hosts ~128 PGs. Single PG capacity ≈ 27.5GiB. Rule: single RBD image ≤ 10× PG capacity (~275GiB). Larger volumes need dedicated pool with higher pg_num.

Thin Provisioning Overcommit : Declared capacity limit = pool usable × 3 (empirical). Alert at pool %USED > 75%.

Kernel Tuning (/etc/sysctl.d/90-ceph-csi.conf) :

# TCP window for 10GbE + MTU 9000, sized for worst-case RTT (deep-scrub 10ms)
net.core.rmem_max = 33554432
net.core.wmem_max = 33554432
net.ipv4.tcp_rmem = 4096 2097152 33554432
net.ipv4.tcp_wmem = 4096 2097152 33554432
# Keepalive for long-lived RBD connections
net.ipv4.tcp_keepalive_time = 300
net.ipv4.tcp_keepalive_intvl = 30
net.ipv4.tcp_keepalive_probes = 5
# File descriptors for dense containers
fs.file-max = 4194304
fs.nr_open = 2097152
# Reduce dirty ratio to limit fsync spikes
vm.dirty_ratio = 10
vm.dirty_background_ratio = 5
vm.swappiness = 1  # not 0, avoids kswapd issues

Window sized for worst-case RTT: 1.25GB/s × 10ms = 12.5MB, so 32MB provides headroom. vm.swappiness=1 not 0 to keep kswapd active.

kubelet fd limits via systemd drop-in ( /etc/systemd/system/kubelet.service.d/20-limits.conf):

[Service]
LimitNOFILE=1048576
LimitNPROC=infinity
TasksMax=infinity

Must run systemctl daemon-reload && systemctl restart kubelet; daemon-reload alone insufficient. Verify via /proc/<pid>/limits.

NVMe Scheduler : Use none (not mq-deadline) via udev rule:

ACTION=="add|change", KERNEL=="nvme[0-9]*n[0-9]*", ATTR{queue/scheduler}="none", ATTR{queue/nr_requests}="1024"

MTU 9000 : Verify end-to-end with ping -M do -s 8972 <peer> (8972 + 28 byte headers = 9000). ip link only shows local config.

7. StorageClass Field-by-Field

apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: ceph-rbd-ssd
  annotations:
    storageclass.kubernetes.io/is-default-class: "false"
provisioner: rbd.csi.ceph.com
parameters:
  clusterID: 8f4e2b1a-7c93-4d05-9a1e-3b6d2c8f5a70  # must match csi-config-map key
  pool: k8s-ssd
  imageFeatures: layering,exclusive-lock,object-map,fast-diff  # object-map,fast-diff depend on exclusive-lock
  csi.storage.k8s.io/fstype: xfs
  csi.storage.k8s.io/provisioner-secret-name: rbd-secret
  csi.storage.k8s.io/provisioner-secret-namespace: ceph-csi
  csi.storage.k8s.io/controller-expand-secret-name: rbd-secret
  csi.storage.k8s.io/controller-expand-secret-namespace: ceph-csi
  csi.storage.k8s.io/node-stage-secret-name: rbd-secret
  csi.storage.k8s.io/node-stage-secret-namespace: ceph-csi
reclaimPolicy: Delete
allowVolumeExpansion: true
volumeBindingMode: WaitForFirstConsumer
mountOptions:
  - noatime
  - discard  # real-time TRIM, but each unmap is synchronous RPC; consider fstrim for IO-sensitive workloads

Four secret annotations must all be present; missing node-stage-secret causes NodeStageVolume failure with "secrets not found". volumeBindingMode: WaitForFirstConsumer delays binding until pod schedules, enabling topology-aware provisioning.

8. Four-Dimensional Config Classification

① Must-change (won't work otherwise) : clusterID, pool, secret names/namespaces, MON addresses, nodeSelector for node DaemonSet.

② Coupled pairs (adjust together) : maxPods ↔ RBD map limit (fd budget); volumeBindingMode ↔ node topology labels; reclaimPolicy ↔ backup/snapshot strategy; MTU ↔ tcp_mtu_probing (fix MTU, don't rely on probing).

③ Performance tuning (calculate, don't copy) : maxPods = min(memoryGB/0.5, CPU/0.25) = 128 for 32C/128G. With 1.2 volumes/pod → ~154 RBD maps → fd budget. imageFeatures impact: fast-diff reduces 100GiB snapshot diff from ~303ms to ~96ms. object-map+fast-diff memory overhead ~64KB per 1TiB volume (negligible).

④ Absolute red lines (changing loses data or causes split-brain) : disabling exclusive-lock → silent corruption; changing volume fstype → mount failure; modifying PV volumeHandle → CSI looks for non-existent image; frequent pg_num changes → rebalance storms; manual monmap edits → cluster outage.

9. Troubleshooting: Five Objects, Three Commands, PromQL

First check five objects (not logs):

kubectl -n ns get pvc,pv
kubectl -n ns describe pvc name | sed -n '/Events/,$p'
kubectl get sc name -o yaml | grep -E 'BindingMode|Expansion'
kubectl -n ceph-csi get pods -o wide
kubectl get volumeattachment | grep -c Bound

Under WaitForFirstConsumer, PVC with no consumer stays Pending with empty Events — this is design, not failure.

Locate volume physically :

# PV volumeHandle & nodeAffinity
kubectl get pv name -o jsonpath='{.spec.csi.volumeHandle}{"
"}'
kubectl get pv name -o jsonpath='{.spec.nodeAffinity}{"
"}'
# Ceph side
rbd info pool/csi-vol-<uuid>
rbd du pool/csi-vol-<uuid>
# Node side
ssh node 'lsblk -o NAME,SIZE,TYPE,MOUNTPOINT | grep -E "rbd|globalmount"'
ssh node 'rbd showmapped'

Mount stuck? Check three log sources in order : pod events → node name → csi-rbdplugin logs on that node. already being used by another node indicates stale VolumeAttachment. Query:

kubectl get volumeattachment -o custom-columns='NAME:.metadata.name,NODE:.spec.nodeName,PV:.spec.source.persistentVolumeName,ATT:.status.attached'

PromQL alerts (80% coverage) :

# PVC Pending >5min (exclude WaitForFirstConsumer normal)
count(kube_persistentvolumeclaim_status_phase{phase="Pending"} == 1 unless on(namespace,persistentvolumeclaim) kube_persistentvolumeclaim_status_phase{phase="Bound"} == 1) > 0
# CSI provisioner gRPC error rate >1%
sum(rate(csi_sidecar_operations_seconds_count{driver_name="rbd.csi.ceph.com",grpc_status_code!="OK"}[5m])) / sum(rate(csi_sidecar_operations_seconds_count{driver_name="rbd.csi.ceph.com"}[5m])) > 0.01
# Volume usage >85% (only when pod running)
(kubelet_volume_stats_used_bytes / kubelet_volume_stats_capacity_bytes) > 0.85
# Ceph: OSD nearfull, PG not active+clean, RBD slow ops, MON quorum
(ceph_cluster_total_used_bytes / ceph_cluster_total_bytes) > 0.80
(ceph_pg_total - ceph_pg_clean) > 0
rate(ceph_rbd_write_latency_sum[5m]) / rate(ceph_rbd_write_ops[5m]) > 0.05
ceph_mon_quorum_status < 3

Three daily one-liners : find PVs with missing Ceph images, find Released PVs, find orphan globalmounts.

10. Three Deep-Dive Failure Cases

Case 1: PVC Expansion Succeeds, Pod df Unchanged

Symptom : PVC/PV/Ceph show 800GiB, pod df shows 500GiB for 6 hours. kubelet_volume_stats_capacity_bytes stuck at 500GiB.

Evidence : PVC Condition Resizing=True for 4h. ControllerExpandVolume succeeded (logs show resize to 800GiB OK). NodeExpandVolume failed: xfs_growfs failed: ... not a mounted XFS filesystem.

Root Cause : CSI v3.16 with Kubernetes v1.34. Kubelet changed NodeExpandVolume staging_target_path semantics; old CSI received pod bind mount path (overlayfs) instead of globalmount, causing xfs_growfs to reject.

Fix : Upgrade ceph-csi to v3.18.2 via operator (Helm deprecated v3.18, removed v3.19). Restart pod to trigger NodeStageVolume + NodeExpandVolume. Verified via df -h and xfs_info (blocks × bsize = 800GiB, agcount increased). Irreversible — XFS doesn't shrink; wrong expansion requires new volume + rsync.

Case 2: Pod Rebuild Stuck in ContainerCreating, Multi-Attach Phantom

Symptom : Deployment rolling update, new pod on node-02 stuck 12min with Multi-Attach error. Old pod on node-01 Terminated 8min ago.

Evidence : rbd showmapped on node-01 still shows /dev/rbd0 mapped. VolumeAttachment shows two entries for same PV: node-01 attached=true, node-02 attached=false with Multi-Attach error.

Root Cause : NodeUnstageVolume failed with target is busy. kubelet doesn't retry, leaving attachment stuck. fuser -vm revealed filebeat (PID 8841) tailing logs under the globalmount, plus a stray bash shell.

Fix : Stop filebeat, verify no holders, umount globalmount, rbd unmap /dev/rbd0 (order critical: umount before unmap), delete stale VolumeAttachment. Pod starts in 18s. Prevention : Move filebeat to /var/log/pods (symlink), add mountPropagation: HostToContainer without bind mounts. Monitor rbd showmapped count vs pod volume count.

Case 3: rbd map "No space left on device" but Pool 40% Free

Symptom : New PVCs Pending, provisioner logs No space left on device. ceph df shows 58% used, no quotas.

Root Cause : Ceph's MAX AVAIL based on emptiest OSD, but rbd create checks each PG's target OSD set for the fullest OSD. Three OSDs at 91% usage (VAR=1.62) blocked new PG placement. Balancer was off ( active: false).

Fix : Enable balancer in upmap mode (adjusts pg-upmap, no data migration): ceph balancer mode upmap; ceph balancer on. Throttle recovery:

osd_max_backfills=1, osd_recovery_max_active=3, osd_recovery_sleep_ssd=0.1

. Watched VAR drop from 1.62 → 1.08 over 47min. PVC creation restored (8s Bound). Rollback :

ceph balancer off; ceph osd set nobackfill; ceph osd set norecover

(order matters). Alert on max(VAR) > 1.3 for 30min.

11. Common Troubleshooting Pattern

Phase : Blocked Layer — Case 1: Node filesystem expand; Case 2: Stale attachment; Case 3: Create-time PG water level.

Key Evidence : Case 1: xfs_growfs refusal; Case 2: target is busy; Case 3: VAR > 1.2.

Fix Direction : Case 1: Upgrade CSI align semantics; Case 2: Release holder + delete zombie; Case 3: Enable balancer.

Rollback Possible : Case 1: No (irreversible); Case 2: Yes; Case 3: Partial.

Rule : CSI error contradicting Ceph metrics → 90% Kubernetes object state (attachment/PV/Pod). Ceph metrics abnormal (PG not clean, OSD down, VAR high) → genuine storage fault (errors show as connection/timeouts).

12. Production Change Management

SC mountOptions : Scope: New volumes only; Disruption: No; Rollback: N/A.

SC reclaimPolicy : Scope: New volumes only; Disruption: No; Rollback: N/A.

Expand PVC : Scope: Single volume, online; Disruption: No; Rollback: Impossible.

Upgrade CSI controller : Scope: New create/delete/expand; Disruption: Brief; Rollback: Rollback image.

Upgrade CSI node plugin : Scope: All volumes on node; Disruption: Yes; Rollback: Restart pods.

Change pool pg_num : Scope: Entire pool; Disruption: Perf jitter; Rollback: Impossible.

Enable balancer : Scope: Whole cluster; Disruption: Perf jitter; Rollback: Disable.

Key Insight : SC mountOptions changes don't affect existing PVs (copied at creation). PV patch doesn't remount running pods — must recreate pod. PVC expansion irreversible (XFS no shrink, ext4 shrink requires unmount+fsck).

13. Two Operational Scripts

Script 1: csi-baseline-check.sh — Pre-deployment read-only validation (kernel modules rbd/nbd, storage NIC MTU 9000 end-to-end, MON ports 6789/3300, fd limits, disk space, clock skew <0.5s for cephx, pool existence, cephx user, zombie mappings). Returns OK/WARN/FAIL summary. Example catches: missing nbd (breaks fstrim), MTU break at one MON (large IO hangs), clock skew 1.84s (cephx rejects).

Script 2: csi-orphan-clean.sh — Safe orphan cleanup with mandatory --apply flag and interactive YES confirmation. Collects live volume inodes from /var/lib/kubelet/pods, scans CSI globalmounts, classifies as HOLD (still mounted or referenced by pod) or CAND (unmounted, unreferenced). Only CAND removed. Then cleans stale rbd mappings where device gone. Dry-run by default.

14. Rollback Playbooks

CSI version : Patch CephCSI CR image back, rollout status. Precondition: no new volumes created with new features.

PVC expansion :

kubectl patch pvc --type=json -p='[{"op":"remove","path":"/spec/resources/requests/storage"}]'

only works via RecoverVolumeExpansionFailure feature gate; already-expanded volumes cannot shrink.

Balancer :

ceph balancer off; ceph osd set nobackfill; ceph osd set norecover

(order critical). Verify business metrics, then unset.

15. Six Engineering Iron Laws

PVC Pending? Check volumeBindingMode first. WaitForFirstConsumer + no consumer = Pending with empty Events — by design.

CSI expansion is two-phase: controller resizes block device, node resizes filesystem. kubectl get pvc shows new size after phase 1; df is final acceptance.

Multi-Attach: 8/10 times it's a zombie attachment, not RWO conflict. Check volumeattachment for duplicate PV, rbd showmapped for leftovers. target is busy culprit usually outside business container: log agents, stray exec shells, tail -f. Find with fuser -vm. No space left on device ≠ capacity full. Check ceph osd df VAR column; single hot OSD blocks new PG placement despite low global %USED.

SC changes don't affect existing volumes; PV changes don't affect mounted volumes. mountOptions takes effect on next NodeStageVolume (pod recreate).

Final meta-rule: Schedule storage change windows for worst-case duration. A 3-minute test upgrade may take 40 minutes in production (sequential node restarts, mount recovery). A 30-minute window has far higher abort probability than a 2-hour window.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

Published

AI-assisted summary

Report an issue with this article
Cloud NativeKubernetesTroubleshootingStorageCSICephProductionRBD

Reader feedback

Was this useful?

Useful0

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion