Skip to content
Kubernetes day 2 · Chapter 15 of 20 Day 13: Cleanup and capacity

Day 13: Cleanup and capacity

Goal: Find and remove leftovers from upgrades and rollouts, set and enforce requests and limits as the basis for capacity planning, keep the nodes’ disks under control · Duration: approx. 60 min · Prerequisite: Day 12

Briefing

  • Three upgrades, one restore and many rollouts leave traces: old images on every node, empty ReplicaSets, growing journals. None of this is a fault, but all of it together eats space and clarity.
  • The scheduler does not plan capacity by what Pods consume, but by what they request (requests). For the scheduler, a Pod without requests counts as zero.
  • Today you measure both: what the cluster really consumes and what it has booked according to requests. The gap between the two is the risk.
Term Meaning
Request guaranteed amount, basis for the scheduler
Limit upper bound, hard for memory (OOM kill)
QoS class Guaranteed, Burstable or BestEffort, determines the order of eviction
LimitRange defaults and bounds per namespace

Drill 1: Consumption versus planning

mkdir -p ~/day2/tag13 && cd ~/day2/tag13
kubectl top nodes
for n in cp1 cp2 cp3; do
  kubectl describe node $n | grep -E '^  (cpu|memory) '
done

Expected:

NAME   CPU(cores)   CPU(%)   MEMORY(bytes)   MEMORY(%)
cp1    794m         19%      1288Mi          10%
cp2    550m         27%      2291Mi          60%
cp3    401m         20%      1240Mi          32%
  cpu                950m (23%)  1 (25%)
  memory             380Mi (3%)  1194Mi (10%)
  cpu                850m (42%)  1 (50%)
  memory             180Mi (4%)  1194Mi (31%)
  cpu                750m (37%)  1 (50%)
  memory             110Mi (2%)  1Gi (26%)

The columns from describe are requests and limits. cp2 uses 60 % of its memory, but according to requests only 4 % is booked. The scheduler thinks cp2 is almost empty and would happily place more Pods there.

Who requests nothing?

kubectl get pods -A -o json | jq -r '.items[]
  | select([.spec.containers[].resources.requests.memory] | any(. == null))
  | "\(.metadata.namespace)/\(.metadata.name)"' | head -8
kubectl -n demo get deploy web shop \
  -o jsonpath='{range .items[*]}{.metadata.name}: {.spec.template.spec.containers[0].resources}{"\n"}{end}'

Expected:

demo/last
demo/shop-fb966798b-pztbh
demo/shop-fb966798b-tql5d
demo/web-7fd857fd9c-hsqtw
demo/web-7fd857fd9c-sm5bv
demo/web-7fd857fd9c-w45wg
kube-system/cilium-cw7x4
kube-system/cilium-envoy-c26h2
web: {}
shop: {}

Your own workloads without any values, plus Cilium and all static Pods of the control plane (those only request CPU). top shows the biggest consumer:

kubectl top pods -A --sort-by=memory | head -4

Expected:

NAMESPACE     NAME                               CPU(cores)   MEMORY(bytes)
kube-system   kube-apiserver-cp2                 206m         403Mi
kube-system   kube-apiserver-cp1                 133m         363Mi
kube-system   kube-apiserver-cp3                 109m         249Mi

The API server, without a memory request. On the tight nodes with 4 GB, this is the item you have to keep in mind when planning.

Save your progress? Sign up for free

Drill 2: Empty ReplicaSets

kubectl -n demo get rs
kubectl get deploy -A -o custom-columns=NS:.metadata.namespace,NAME:.metadata.name,HIST:.spec.revisionHistoryLimit

Expected:

NAME              DESIRED   CURRENT   READY   AGE
shop-56d7b69945   0         0         0       20h
shop-745bdbb55d   0         0         0       20h
shop-76d76f687d   0         0         0       20h
shop-7cd57755b7   0         0         0       20h
shop-fb966798b    2         2         2       19h
web-6b447988f     0         0         0       19h
web-75d549d885    0         0         0       19h
web-776b55fcfb    0         0         0       21h
web-7fd857fd9c    3         3         3       3m23s
NS            NAME              HIST
demo          shop              10
demo          web               10
kube-system   cilium-operator   10
kube-system   coredns           10
kube-system   metrics-server    10

Every rollout leaves behind a ReplicaSet with zero Pods. That is intended: it is the basis for kubectl rollout undo. Ten per Deployment are usually too many; three are enough for a rollback.

Save your progress? Sign up for free

Drill 3: Setting requests, shortening the history

Both in one patch, so a single rollout. The load runs as it did yesterday:

kubectl -n demo delete pod last
sed "s#http://web.demo#http://shop.demo#" ~/day2/tag00/last.yaml | kubectl apply -f -
kubectl -n demo wait --for=condition=Ready pod/last
for d in web shop; do
  kubectl -n demo patch deploy $d --type=json -p='[
    {"op":"add","path":"/spec/revisionHistoryLimit","value":3},
    {"op":"add","path":"/spec/template/spec/containers/0/resources",
     "value":{"requests":{"cpu":"10m","memory":"16Mi"},"limits":{"memory":"64Mi"}}}]'
done
kubectl -n demo rollout status deploy/web --timeout=120s | tail -1
kubectl -n demo rollout status deploy/shop --timeout=120s | tail -1
kubectl -n demo get rs

Expected:

deployment.apps/web patched
deployment.apps/shop patched
deployment "web" successfully rolled out
deployment "shop" successfully rolled out
NAME              DESIRED   CURRENT   READY   AGE
shop-56d7b69945   0         0         0       20h
shop-76d76f687d   0         0         0       20h
shop-86856b859d   2         2         2       27s
shop-fb966798b    0         0         0       19h
web-6b447988f     0         0         0       19h
web-75d549d885    0         0         0       19h
web-7fd857fd9c    0         0         0       4m35s
web-855b64d99b    3         3         3       27s

Per Deployment, the current ReplicaSet and three old ones remain; the controller deleted the rest. The request values come from kubectl top (1–5 MB, a few millicores) plus a reserve. And the QoS class has changed:

kubectl -n demo get pods -o custom-columns=NAME:.metadata.name,QOS:.status.qosClass
kubectl -n demo logs last | wc -l
kubectl -n demo logs last | awk '$2 != 200' | wc -l

Expected (abridged, an old shop Pod is just terminating):

NAME                    QOS
last                    BestEffort
shop-86856b859d-l94s7   Burstable
shop-86856b859d-pxwzg   Burstable
web-855b64d99b-bpdjl    Burstable
web-855b64d99b-pvm2t    Burstable
web-855b64d99b-tvf57    Burstable
202
0

Under memory pressure, BestEffort is evicted first, Burstable after that. The rollout ran without errors: 0 out of 202 requests.

Save your progress? Sign up for free

Drill 4: Enforcing defaults

The next deploy without requests is sure to come. A LimitRange sets defaults and bounds for every container in the namespace:

cat > limitrange.yaml <<'EOF'
apiVersion: v1
kind: LimitRange
metadata:
  name: standard
  namespace: demo
spec:
  limits:
  - type: Container
    defaultRequest:
      cpu: 10m
      memory: 32Mi
    default:
      memory: 128Mi
    max:
      memory: 512Mi
EOF
kubectl apply -f limitrange.yaml
kubectl -n demo run ohne --image=busybox:1.37 --restart=Never -- sleep 3600
kubectl -n demo get pod ohne -o jsonpath='{.spec.containers[0].resources}{"\n"}{.status.qosClass}{"\n"}'

Expected:

limitrange/standard created
pod/ohne created
{"limits":{"memory":"128Mi"},"requests":{"cpu":"10m","memory":"32Mi"}}
Burstable

And for anyone who wants too much:

kubectl -n demo run zuviel --image=busybox:1.37 --restart=Never --overrides='{"spec":{"containers":[
  {"name":"zuviel","image":"busybox:1.37","command":["sleep","3600"],
   "resources":{"limits":{"memory":"1Gi"}}}]}}'
kubectl -n demo delete pod ohne --now

Expected:

Error from server (Forbidden): pods "zuviel" is forbidden: maximum memory usage per Container is 512Mi, but limit is 1Gi
pod "ohne" deleted from demo namespace

The LimitRange only applies at creation time. Existing Pods such as last keep their values until they are recreated.

Save your progress? Sign up for free

Drill 5: Old images

Every node holds the images of all previous versions:

sudo crictl images | grep -E 'kube-apiserver|etcd|coredns'

Expected:

registry.k8s.io/coredns/coredns                 v1.13.1             aa5e3ebc0dfed       23.6MB
registry.k8s.io/coredns/coredns                 v1.14.2             38667dd9be96c       23.3MB
registry.k8s.io/coredns/coredns                 v1.14.6             520212b8b0fcd       23.8MB
registry.k8s.io/etcd                            3.6.6-0             0a108f7189562       23.6MB
registry.k8s.io/etcd                            3.6.8-0             ee85eb1f0edd2       22.9MB
registry.k8s.io/etcd                            3.7.0-0             270fbeb697171       22.3MB
registry.k8s.io/kube-apiserver                  v1.35.10            2b6a34f9e844b       27.9MB
registry.k8s.io/kube-apiserver                  v1.36.6             24c051fef120b       29.9MB
registry.k8s.io/kube-apiserver                  v1.37.2             7a918dfe48696       31.2MB

The kubelet cleans up images on its own, but only once the disk is 85 % full (imageGCHighThresholdPercent). The kubelet itself shows the effective values:

kubectl get --raw /api/v1/nodes/cp1/proxy/configz | jq '.kubeletconfig |
  {containerLogMaxSize, containerLogMaxFiles, imageGCHighThresholdPercent,
   imageGCLowThresholdPercent, evictionHard}'

Expected:

{
  "containerLogMaxSize": "10Mi",
  "containerLogMaxFiles": 5,
  "imageGCHighThresholdPercent": 85,
  "imageGCLowThresholdPercent": 80,
  "evictionHard": {
    "imagefs.available": "15%",
    "imagefs.inodesFree": "5%",
    "memory.available": "100Mi",
    "nodefs.available": "10%",
    "nodefs.inodesFree": "5%"
  }
}

At 85 % the kubelet removes images, at 90 % disk usage (nodefs.available: 10%) it starts evicting Pods. There is little room in between. Better to clean up yourself:

df -h / | tail -1
sudo crictl images -q | wc -l
sudo crictl rmi --prune | tail -3
df -h / | tail -1
sudo crictl images -q | wc -l
sudo du -sh /var/lib/containerd

Expected:

/dev/sda1        77G   12G   65G  16% /
33
Deleted: docker.io/library/busybox:1.37
Deleted: registry.k8s.io/kube-proxy:v1.35.10
Deleted: registry.k8s.io/kube-controller-manager:v1.35.10
/dev/sda1        77G  9.4G   68G  13% /
15
2.4G    /var/lib/containerd

18 fewer images, containerd uses 2.4 GB less. --prune deletes everything that no container is currently using. A Pod that later lands on this node then pulls its image again. In a cluster without internet access or with a slow registry, think about this first.

Save your progress? Sign up for free

Drill 6: Limiting the journal

The kubelet rotates container logs (10 MiB, five files per container). The system journal grows up to 10 % of the file system, at most 4 GB:

journalctl --disk-usage
sudo mkdir -p /etc/systemd/journald.conf.d
printf '[Journal]\nSystemMaxUse=200M\n' | sudo tee /etc/systemd/journald.conf.d/groesse.conf
sudo systemctl restart systemd-journald
journalctl --disk-usage

Expected:

Archived and active journals take up 335.4M in the file system.
[Journal]
SystemMaxUse=200M
Archived and active journals take up 198.7M in the file system.

On restart, journald sticks to the limit right away and deletes the oldest files.

Save your progress? Sign up for free

Exercise: Speed Drills

  1. Show the five Pods with the highest CPU load in the cluster. Target time: 30 s
  2. Show the QoS class of all Pods in demo. Target time: 1 min
  3. Show how much space the images take up on the node. Target time: 30 s

Solution

kubectl top pods -A --sort-by=cpu | head -6
kubectl -n demo get pods -o custom-columns=NAME:.metadata.name,QOS:.status.qosClass
sudo crictl imagefsinfo | jq '.status.imageFilesystems[0].usedBytes.value'

Save your progress? Sign up for free

Checkpoint

kubectl -n demo get rs --no-headers | wc -l

Expected: 8 (per Deployment the current one and three old ones)

kubectl -n demo get limitrange

Expected: standard

Challenge

How many more web Pods (requesting 10m CPU, 16Mi memory) fit on cp2? Work it out from the node’s values before you try it.

Hint: There are three limits, not two.

Solution

kubectl get node cp2 -o jsonpath='{.status.allocatable.pods}{"\n"}'
kubectl get pods -A --field-selector spec.nodeName=cp2 --no-headers | wc -l
kubectl describe node cp2 | grep -E '^  (cpu|memory) '

Expected:

110
11
  cpu                860m (43%)  1 (50%)
  memory             196Mi (5%)  1258Mi (32%)
Limit Calculation Pods
CPU (2000m − 860m) / 10m 114
Memory (3815Mi − 196Mi) / 16Mi 226
Pods per node 110 − 11 99

The tightest limit is the number of Pods per node (maxPods, default 110), not CPU or memory. And the calculation only holds on paper: cp2 already uses 60 % of its memory, mostly because of the API server without a memory request. 99 new Pods would drive it into eviction, even though the scheduler admits them.

Save your progress? Sign up for free

Cleanup

Nothing to roll back. The LimitRange, the shorter history and the journal limit stay. Clean up the images on cp2 and cp3 the same way when you get the chance.

Interview Note

  • What values does the scheduler plan by? By requests, not by consumption. Pods without requests count as zero and make the planning blind.
  • What is a LimitRange? A per-namespace object that gives defaults to containers without values and enforces upper or lower bounds when the Pod is created.
  • When does the kubelet clean up images? From 85 % disk usage down to 80 %. From 90 %, it evicts Pods.

Enterprise Note

  • Estimating requests correctly is a discipline of its own. The Vertical Pod Autoscaler in “Off” mode recommends values from real consumption without setting them.
  • ResourceQuotas limit the total per namespace and are the lever for tenant separation. Together with LimitRanges, they are mandatory in shared clusters.
  • Capacity planning needs time series, not a snapshot: requests versus consumption over weeks, per node type. Tools such as Kubecost or OpenCost also turn this into costs.

Contents

More