# Workloads and Scheduling: Rolling Updates, Resource Limits and Autoscaling

> Deployment rolling updates and rollbacks, requests/limits, taints/tolerations and affinity, plus HPA autoscaling added in the 2025 exam revision

- URL: https://lcxlab.com/en/post/cka-workloads-scheduling
- Author: Miles Hsu
- Published: 2026-10-30
- Category: DevOps
- Series: Certified Kubernetes Administrator (CKA) #5
- Tags: CKA, Kubernetes
- License: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/deed.en)

---

Workloads & Scheduling makes up 15% of the CKA. The questions are usually not hard, but there are a lot of them and they are easy points, so how fluent you are decides whether you save enough time for the troubleshooting questions later. This post uses the three-node cluster built in the previous post (`k8s-cp1`, `k8s-w1`, `k8s-w2`) for hands-on practice, starting with Deployment rolling updates, moving through resource limits and scheduling controls, and ending with the autoscaling topic added in the 2025 revision.

[Building a kubeadm Cluster (Part 2)](https://lcxlab.com/en/post/cka-kubeadm-cluster)

---

## Deployment Rolling Updates and Rollbacks

In Kubernetes we almost never create bare Pods to run a service. Instead we create a Deployment, which keeps the replica count, rolls out new versions, and can go back to the previous version when something breaks.

### How Deployments, ReplicaSets and Pods Relate

Each layer manages the one below it:

```mermaid
flowchart TB
    D["Deployment<br/>Manages versions and update strategy"]
    RS1["ReplicaSet (revision 1)<br/>nginx:1.29 → replicas: 0"]
    RS2["ReplicaSet (revision 2)<br/>nginx:1.30 → replicas: 3"]
    P1["Pod"]
    P2["Pod"]
    P3["Pod"]

    D --> RS1
    D --> RS2
    RS2 --> P1
    RS2 --> P2
    RS2 --> P3

    classDef deploy fill:#dbeafe,stroke:#2563eb,color:#1e3a8a
    classDef rs fill:#dcfce7,stroke:#16a34a,color:#14532d
    classDef old fill:#f3f4f6,stroke:#9ca3af,color:#4b5563
    classDef pod fill:#ede9fe,stroke:#7c3aed,color:#4c1d95

    class D deploy
    class RS2 rs
    class RS1 old
    class P1,P2,P3 pod
```
> Figure 1: A Deployment manages Pods through ReplicaSets; old ReplicaSets are kept around for rollbacks

- **Pod**: the smallest unit that actually runs containers. When it dies it is gone; it does not recreate itself.
- **ReplicaSet**: keeps "N identical Pods" running and replaces any that go missing.
- **Deployment**: handles "versions". Every time the Pod template changes (for example a new image), the Deployment creates a new ReplicaSet, then gradually scales the old one down to 0 and the new one up to the target. That is a rolling update.

The old ReplicaSet is not deleted, only scaled to 0. Rolling back simply scales it back up. How many old versions are kept is set by `spec.revisionHistoryLimit`, which defaults to 10.

```bash
k create deployment nginx --image=nginx:1.29 --replicas=3
k get deploy,rs,po -l app=nginx
```

ReplicaSet and Pod names include the pod-template-hash, for example `nginx-7c79c4bf97-xxxxx`, so the name tells you which ReplicaSet a Pod came from.

>[!NOTE] Side note: ReplicaSets and self-healing
>How ReplicaSets and ReplicationControllers bring Pods back after they crash leans toward CKAD and isn't a focus of the CKA, so it's covered separately here:
>
>[Kubernetes Self-Healing](https://lcxlab.com/en/post/kubernetes-self-healing)

### Rolling Update Strategy: maxSurge and maxUnavailable

A Deployment has two update strategies:

| Strategy | Behavior | When to use |
|--|--|--|
| `RollingUpdate` (default) | Old and new Pods are swapped gradually with no downtime | Most stateless services |
| `Recreate` | All old Pods are killed first, then new ones are created, with downtime in between | Old and new versions cannot coexist, e.g. they would fight over the same database schema |

`RollingUpdate` is paced by two parameters:

- **maxSurge**: how many Pods may exist *above* the desired replica count during the update.
- **maxUnavailable**: how many Pods may be *unavailable* during the update.

Both accept a number or a percentage, and both default to `25%` (maxSurge rounds up, maxUnavailable rounds down).

```yaml
spec:
  replicas: 4
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
```

With `replicas: 4`, `maxSurge: 1` and `maxUnavailable: 0`, there are at most 5 Pods during the update and at least 4 available at all times: one new Pod is started, and only after it is Ready is one old Pod removed, one at a time. This is the most conservative setting, at the cost of a slower rollout.

The opposite, `maxSurge: 0` and `maxUnavailable: 1`, removes an old Pod first and then adds a new one. It uses no extra resources, which suits clusters that are short on capacity.

>[!TIP] 💡 Exam tip
>If a question says "no service interruption during the update", set `maxUnavailable` to `0`. If it asks you to switch to Recreate, delete the whole `rollingUpdate` block, otherwise the API Server rejects it (`Recreate` cannot carry `rollingUpdate` parameters).

### kubectl rollout: Status, History and Rollback

The quickest way to trigger an update is `kubectl set image`:

```bash
# Format: deployment/<name> <container-name>=<new image>
k set image deployment/nginx nginx=nginx:1.30

# Watch the rollout until it finishes
k rollout status deployment/nginx
```

After the update you can check the history:

```bash
k rollout history deployment/nginx

# Show the Pod template of a specific revision
k rollout history deployment/nginx --revision=2
```

The `CHANGE-CAUSE` column is empty by default. The old way was to add `--record`, but that flag is deprecated; now you write the annotation directly:

```bash
k annotate deployment/nginx kubernetes.io/change-cause="update to nginx:1.30"
```

Roll back when the new version has problems:

```bash
# Go back to the previous revision
k rollout undo deployment/nginx

# Go back to a specific revision
k rollout undo deployment/nginx --to-revision=1
```

![151941](https://lcxlab.com/images/posts/cka-workloads-scheduling/151941.webp)
> The revision number goes up after a rollback

![152140](https://lcxlab.com/images/posts/cka-workloads-scheduling/152140.webp)
> Go back to a specific revision.

A rollback is itself an "update", so the revision number goes up after a rollback instead of returning to the old number. This is easy to misread the first time you look at the history.

Other useful `rollout` subcommands:

```bash
# Pause: further changes don't trigger a rollout right away, handy when editing several fields at once
k rollout pause deployment/nginx
k set image deployment/nginx nginx=nginx:1.31
k set resources deployment/nginx -c nginx --limits=cpu=200m,memory=256Mi
k rollout resume deployment/nginx

# Recreate all Pods with a rolling update without changing anything (e.g. after a ConfigMap update)
k rollout restart deployment/nginx
```

---

## Injecting Configuration: ConfigMaps and Secrets

If configuration is baked into the image, every config change means rebuilding the image. Kubernetes instead keeps regular configuration in ConfigMaps and sensitive data in Secrets, and injects them into Pods.

```bash
# From literal values
k create configmap app-config --from-literal=APP_MODE=prod --from-literal=APP_PORT=8080

# From a file: the key is the file name, the value is the file content
k create configmap nginx-conf --from-file=default.conf

# Secrets are almost the same, with an extra type: generic
k create secret generic db-secret --from-literal=DB_USER=admin --from-literal=DB_PASS='P@ssw0rd'
```

>[!WARNING] Secrets are only base64, not encryption
>The values shown by `k get secret db-secret -o yaml` are just base64-encoded; `echo <value> | base64 -d` recovers them. The main differences from a ConfigMap are that RBAC permissions can be controlled separately, and kubelet keeps Secrets in memory (tmpfs) instead of writing them to the node's disk. To actually encrypt them in etcd you need to configure Encryption at Rest.

### Injecting as Environment Variables

To pick only specific keys:

```yaml
spec:
  containers:
  - name: app
    image: nginx
    env:
    - name: APP_MODE
      valueFrom:
        configMapKeyRef:
          name: app-config
          key: APP_MODE
    - name: DB_PASS
      valueFrom:
        secretKeyRef:
          name: db-secret
          key: DB_PASS
```

To pull in every key of a ConfigMap / Secret:

```yaml
    envFrom:
    - configMapRef:
        name: app-config
    - secretRef:
        name: db-secret
```

Note that environment variables are read only once when the container starts. Changing the ConfigMap later does not update running Pods; you need `k rollout restart` to recreate them with the new values.

### Mounting as a Volume

Config-file style content (such as nginx's `default.conf`) is better mounted as files. Each key becomes a file in the mounted directory:

```yaml
spec:
  containers:
  - name: nginx
    image: nginx
    volumeMounts:
    - name: conf
      mountPath: /etc/nginx/conf.d
      readOnly: true
  volumes:
  - name: conf
    configMap:
      name: nginx-conf
```

Secrets work the same way: replace `configMap` with `secret` and `name` with `secretName`.

The advantage of a volume is that after the ConfigMap changes, kubelet syncs the file content within a while (usually under a minute) without recreating the Pod. Files mounted with `subPath`, however, are not updated automatically. Whether the application re-reads the file is up to the application itself.

### command and args: Overriding the Container's Start Command

A Pod's `command` and `args` map to the Dockerfile's `ENTRYPOINT` and `CMD`:

| Dockerfile | Pod spec | Meaning |
|--|--|--|
| `ENTRYPOINT` | `command` | The program to run |
| `CMD` | `args` | Arguments passed to the program |

```yaml
spec:
  containers:
  - name: sleeper
    image: busybox:1.38
    command: ["sleep"]
    args: ["3600"]
```

With only `args`, the image's `ENTRYPOINT` is kept and only the arguments change. With `command`, both the image's `ENTRYPOINT` and `CMD` are ignored.

When generating with `kubectl run`, everything after `--` becomes `args` by default; add `--command` to make it `command`:

```bash
k run sleeper --image=busybox:1.38 --dry-run=client -o yaml -- sleep 3600              # args: [sleep, "3600"]
k run sleeper --image=busybox:1.38 --dry-run=client -o yaml --command -- sleep 3600    # command: [sleep, "3600"]
```

---

## Resource Management

### requests and limits

```yaml
spec:
  containers:
  - name: app
    image: nginx
    resources:
      requests:
        cpu: 250m
        memory: 128Mi
      limits:
        cpu: 500m
        memory: 256Mi
```

- **requests**: the "reservation" used for scheduling. The scheduler decides which node a Pod fits on based only on requests, not on actual usage.
- **limits**: the runtime "ceiling", enforced by kubelet and the container runtime through cgroups.

Exceeding the limit has different consequences for CPU and memory:

| Resource | Units | When the limit is exceeded |
|--|--|--|
| CPU | `1` = 1 core, `250m` = 0.25 core | Throttled: slower, but not killed |
| Memory | `Mi`, `Gi` (binary); `M`, `G` (decimal) | The container is OOMKilled and restarted according to restartPolicy |

The combination of requests and limits also decides a Pod's QoS class. When a node runs low on memory and has to evict Pods, it starts from the lowest class:

| QoS class | Condition | Eviction order |
|--|--|--|
| `Guaranteed` | Every container sets CPU and memory with requests = limits | Last |
| `Burstable` | At least one container sets requests or limits, but not Guaranteed | Middle |
| `BestEffort` | Nothing set at all | First |

```bash
# Change the resources of an existing Deployment
k set resources deployment/nginx -c nginx --requests=cpu=100m,memory=128Mi --limits=cpu=200m,memory=256Mi

# Check a Pod's QoS class
k get pod <pod-name> -o jsonpath='{.status.qosClass}'

# See how much of a node is already taken by requests
k describe node k8s-w1 | grep -A 8 "Allocated resources"
```

When a Pod stays `Pending` and `describe` shows `Insufficient cpu` or `Insufficient memory`, the requests are usually too large to fit in the remaining allocatable resources of any node.

### LimitRange and ResourceQuota

Both are Namespace-scoped objects, but they work at different levels:

- **LimitRange**: applies to a *single Pod / container*. It can give default values to containers without resources, and set a minimum and maximum per container.
- **ResourceQuota**: applies to the *total of the whole Namespace*, for example at most 4 CPU cores and 10 Pods in total.

```yaml
apiVersion: v1
kind: LimitRange
metadata:
  name: default-limits
  namespace: dev
spec:
  limits:
  - type: Container
    defaultRequest:   # applied when requests are missing
      cpu: 100m
      memory: 128Mi
    default:          # applied when limits are missing
      cpu: 500m
      memory: 256Mi
    max:
      cpu: "1"
      memory: 512Mi
```

```bash
# A ResourceQuota can be created with a single command
k create quota dev-quota -n dev --hard=requests.cpu=2,requests.memory=4Gi,limits.cpu=4,limits.memory=8Gi,pods=10

# Show current usage against the limits
k describe quota dev-quota -n dev
```

>[!NOTE] Once a ResourceQuota is in place
>If a ResourceQuota limits compute resources such as `requests.cpu` or `limits.memory`, Pods in that Namespace without resources are rejected outright. That is why it is usually paired with a LimitRange that supplies defaults. Both LimitRange and ResourceQuota are only checked when a Pod is created; running Pods are not affected.

---

## Scheduling Control

After a Pod is created, kube-scheduler decides which node it runs on. Scheduling roughly has two steps: first *filter* out nodes that don't qualify (not enough resources, taints, affinity mismatch…), then *score* the remaining nodes and pick the best. Everything below influences one of these two steps.

```mermaid
flowchart LR
    P["New Pod<br/>(empty nodeName)"]
    F["Filter<br/>resources, nodeSelector,<br/>affinity, taints"]
    S["Score<br/>preferred affinity,<br/>resource spread"]
    B["Bind<br/>write nodeName"]
    K["kubelet<br/>starts containers"]

    P --> F --> S --> B --> K

    classDef step fill:#dbeafe,stroke:#2563eb,color:#1e3a8a
    classDef node fill:#dcfce7,stroke:#16a34a,color:#14532d

    class P,F,S,B step
    class K node
```
> Figure 2: kube-scheduler's scheduling flow

### nodeName and nodeSelector

**nodeName** is the most direct option: it names the node and skips the scheduler entirely:

```yaml
spec:
  nodeName: k8s-w1
  containers:
  - name: nginx
    image: nginx
```

Because the scheduler is bypassed, taints and resource checks don't apply, and a typo in the node name leaves the Pod `Pending` forever. Also, `nodeName` can only be set at creation time; to move the Pod you have to delete and recreate it. This turns out to be very useful in troubleshooting questions where the scheduler is broken.

**nodeSelector** filters by node labels instead:

```bash
k label node k8s-w1 disktype=ssd
k get nodes --show-labels
```

```yaml
spec:
  nodeSelector:
    disktype: ssd
```

nodeSelector only does equality matching, and all conditions must match. For anything more complex, use Node Affinity.

### Node Affinity

Node Affinity is an advanced nodeSelector. It supports operators such as `In`, `NotIn`, `Exists`, `DoesNotExist`, `Gt` and `Lt`, and comes in a hard and a soft flavor:

- **requiredDuringSchedulingIgnoredDuringExecution**: hard rule; if nothing matches, the Pod isn't scheduled.
- **preferredDuringSchedulingIgnoredDuringExecution**: soft rule; matched if possible, otherwise the Pod still goes to another node.

The `IgnoredDuringExecution` suffix means that once the Pod is running, changing the node's labels won't evict it.

```yaml
spec:
  affinity:
    nodeAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
        nodeSelectorTerms:
        - matchExpressions:
          - key: disktype
            operator: In
            values: ["ssd", "nvme"]
      preferredDuringSchedulingIgnoredDuringExecution:
      - weight: 80
        preference:
          matchExpressions:
          - key: zone
            operator: In
            values: ["zone-a"]
```

This YAML is long. Don't memorize it for the exam; copying the example from the official docs at [Assign Pods to Nodes using Node Affinity](https://kubernetes.io/docs/tasks/configure-pod-container/assign-pods-nodes-using-node-affinity/) and editing it is fastest.

>[!NOTE] nodeSelectorTerms vs. matchExpressions
>Multiple items under `nodeSelectorTerms` are **OR**ed: matching any one is enough. Multiple `matchExpressions` within the same item are **AND**ed: all must match.

### Taints and Tolerations

Affinity is a Pod actively *choosing* nodes. Taints work the other way: a node *repels* Pods. Once a node has a taint, only Pods with a matching toleration can be scheduled onto it.

```bash
# Add a taint: key=value:effect
k taint node k8s-w2 gpu=true:NoSchedule

# Remove a taint: append -
k taint node k8s-w2 gpu=true:NoSchedule-

# Show a node's taints
k describe node k8s-w2 | grep -i taint
```

There are three effects:

| effect | New Pods | Running Pods |
|--|--|--|
| `NoSchedule` | Can't be scheduled here | Not affected |
| `PreferNoSchedule` | Avoided if possible, used only when there's nowhere else | Not affected |
| `NoExecute` | Can't be scheduled here | Evicted unless they tolerate it |

To tolerate a taint, add a toleration to the Pod spec:

```yaml
spec:
  tolerations:
  - key: gpu
    operator: Equal
    value: "true"
    effect: NoSchedule
```

When the cluster was built with kubeadm in the previous post, the control plane node was automatically tainted with `node-role.kubernetes.io/control-plane:NoSchedule`. That is why regular Pods never land on `k8s-cp1`.

```bash
k describe node k8s-cp1 | grep -i taint
# Taints: node-role.kubernetes.io/control-plane:NoSchedule
```

>[!WARNING] A toleration doesn't pin a Pod to a node
>A toleration only means the Pod *may* be scheduled on a tainted node, not that it *will* be. To dedicate nodes to certain Pods, combine Taints/Tolerations with Node Affinity: the taint keeps other Pods out, and the affinity pulls the chosen Pods in.

### DaemonSet: One Copy per Node

A DaemonSet makes sure exactly one Pod runs on every (or every matching) node. New nodes get one automatically when they join, and it is cleaned up when a node is removed. Typical uses are per-node agents such as CNI plugins (Calico, Cilium), kube-proxy, log collectors (Fluent Bit) and monitoring (node-exporter).

```bash
k get ds -A
```

`kubectl create` has no daemonset subcommand, so a common exam trick is to generate a Deployment YAML and edit it:

```bash
k create deployment fluent-bit --image=fluent/fluent-bit:5.1 -n kube-system --dry-run=client -o yaml > ds.yaml
```

Then change `kind: Deployment` to `kind: DaemonSet` and remove `replicas`, `strategy` and `status`:

```yaml
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: fluent-bit
  namespace: kube-system
spec:
  selector:
    matchLabels:
      app: fluent-bit
  template:
    metadata:
      labels:
        app: fluent-bit
    spec:
      tolerations:
      - key: node-role.kubernetes.io/control-plane
        operator: Exists
        effect: NoSchedule
      containers:
      - name: fluent-bit
        image: fluent/fluent-bit:5.1
```

DaemonSets are also subject to taints. Only with the toleration for the control plane taint above does it get deployed on `k8s-cp1` too.

>[!NOTE] Side note: StatefulSets
>Besides Deployments and DaemonSets, stateful services such as databases use StatefulSets, which give each Pod a stable name, DNS record and its own PVC. The official CKA course lists them as out of scope and points to CKAD, so they're covered separately here:
>
>[Kubernetes StatefulSets](https://lcxlab.com/en/post/kubernetes-statefulset)

### Static Pods: Managed Directly by kubelet

Normal Pods are created through the API Server and placed by the scheduler. Static Pods are started by kubelet itself from YAML files in a directory on the node, with no API Server and no scheduler involved.

This also solves a chicken-and-egg problem: kube-apiserver is itself a Pod, so who starts it before the API Server exists? kubelet does. In a kubeadm cluster, all four control plane components are static Pods:

```bash
ls /etc/kubernetes/manifests/
# etcd.yaml  kube-apiserver.yaml  kube-controller-manager.yaml  kube-scheduler.yaml
```

Static Pods have a few properties:

- Add a YAML file to the directory and kubelet creates the Pod; delete the file and the Pod goes away; edit the file and the Pod is recreated.
- kubelet creates a matching *mirror Pod* on the API Server, so `kubectl get pods` shows it, with the node name appended, e.g. `kube-apiserver-k8s-cp1`.
- `kubectl delete` doesn't work: kubelet recreates it immediately. To remove it, delete the file on the node.

### Finding staticPodPath and Creating a Static Pod

The static Pod directory isn't always `/etc/kubernetes/manifests`; an exam question may have changed it on some node, so you need to be able to find it. First find kubelet's config file:

```bash
ps aux | grep kubelet | grep -- --config
# ... --config=/var/lib/kubelet/config.yaml ...
```

Then look up `staticPodPath` in it:

```bash
sudo grep staticPodPath /var/lib/kubelet/config.yaml
# staticPodPath: /etc/kubernetes/manifests
```

If the question wants a static Pod on a worker node, SSH to that node and put the YAML there:

```bash
# Generate the YAML on the control plane
k run static-web --image=nginx --dry-run=client -o yaml > static-web.yaml

# Copy it to the worker's staticPodPath
scp static-web.yaml k8s-w1:/tmp/
ssh k8s-w1 sudo mv /tmp/static-web.yaml /etc/kubernetes/manifests/

# Back on the control plane; the name will be static-web-k8s-w1
k get pods -o wide
```

If you change `staticPodPath`, run `sudo systemctl restart kubelet` for it to take effect.

---

## Autoscaling

Since the 2025 revision, Workloads & Scheduling includes "Configure workload autoscaling". Autoscaling in Kubernetes goes in three directions:

| Type | What it adjusts | When to use |
|--|--|--|
| HPA (Horizontal Pod Autoscaler) | The **number** of Pods | Stateless services that need more replicas at peak traffic |
| VPA (Vertical Pod Autoscaler) | Each Pod's **requests / limits** | You don't know what resources to set, or the service is hard to scale horizontally |
| Cluster Autoscaler | The number of **nodes** | Cloud environments that add machines when Pods don't fit |

Cluster Autoscaler depends on a cloud provider's API and is outside the CKA scope, so this post only covers HPA and VPA.

### HPA and metrics-server

HPA is a controller built into kube-controller-manager and needs no installation, but it has to know how much CPU and memory Pods are using, and those numbers come from metrics-server.

>[!TIP]
>HPA itself has been part of Kubernetes for a long time, and the `autoscaling/v2` API, which supports multiple metrics and scaling behavior settings, has been GA since Kubernetes v1.23. Just use `autoscaling/v2` when writing YAML today.

```mermaid
flowchart LR
    K["kubelet<br/>(cAdvisor)"]
    M["metrics-server"]
    A["kube-apiserver<br/>metrics.k8s.io"]
    H["HPA controller<br/>(controller-manager)"]
    D["Deployment<br/>replicas"]

    K -->|"resource usage"| M
    M -->|"registers Metrics API"| A
    H -->|"queries every 15s"| A
    H -->|"adjusts replicas"| D

    classDef node fill:#dcfce7,stroke:#16a34a,color:#14532d
    classDef server fill:#dbeafe,stroke:#2563eb,color:#1e3a8a
    classDef ctrl fill:#fef3c7,stroke:#d97706,color:#78350f

    class K node
    class M,A server
    class H,D ctrl
```
> Figure 3: HPA reads usage through metrics-server and adjusts the replica count

A kubeadm cluster doesn't ship with metrics-server, so install it yourself:

```bash
k apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml
```

In a self-built kubeadm lab, kubelet uses a self-signed certificate, so metrics-server keeps failing certificate verification and never becomes ready (the logs show `x509: cannot validate certificate`). For a lab you can add `--kubelet-insecure-tls` to its args:

```bash
k -n kube-system patch deployment metrics-server --type=json \
  -p='[{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--kubelet-insecure-tls"}]'
```

>[!WARNING] Don't do this in production
>`--kubelet-insecure-tls` skips kubelet certificate verification and is only for labs. In production, kubelet should use serving certificates signed by the cluster CA (set `serverTLSBootstrap: true` and approve the CSRs).

Wait about a minute after installing and confirm metrics are available:

```bash
k top nodes
k top pods -A --sort-by=cpu
```

### Creating an HPA with kubectl autoscale

HPA uses **requests** as the denominator for percentages, so the target Deployment must set resource requests, otherwise the HPA keeps showing `<unknown>`:

```bash
k create deployment php-apache --image=registry.k8s.io/hpa-example --port=80
k set resources deployment/php-apache --requests=cpu=200m --limits=cpu=500m
k expose deployment php-apache --port=80
```

Create the HPA with one command: keep average CPU utilization at 50%, with between 1 and 10 replicas:

```bash
k autoscale deployment php-apache --cpu-percent=50 --min=1 --max=10
k get hpa
```

The command only creates a basic CPU metric. For memory or scaling behavior you need YAML (again, generate a skeleton with `--dry-run=client -o yaml` and edit it):

```yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: php-apache
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: php-apache
  minReplicas: 1
  maxReplicas: 10
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 50
  behavior:
    scaleDown:
      stabilizationWindowSeconds: 120   # default is 300 seconds
```

HPA computes the replica count as:

```text
desiredReplicas = ceil( currentReplicas × currentMetricValue / desiredMetricValue )
```

For example, with 2 replicas, 90% average CPU utilization and a 50% target, `ceil(2 × 90 / 50) = ceil(3.6) = 4`, so it scales to 4.

To see it in action, open another terminal and run a Pod that hammers the service:

```bash
k run load-generator --rm -it --image=busybox:1.38 --restart=Never -- \
  /bin/sh -c "while sleep 0.01; do wget -q -O- http://php-apache; done"
```

Back in the first terminal, `TARGETS` climbs and `REPLICAS` follows:

```bash
k get hpa php-apache --watch
```

After stopping the load generator, the replica count doesn't drop right away. To avoid flapping when traffic fluctuates, HPA scale-down by default looks at the recommendations from the past 5 minutes and takes the highest one, so it takes a while to shrink back.

### VPA: Vertical Scaling

VPA is not built into Kubernetes. It lives in the [kubernetes/autoscaler](https://github.com/kubernetes/autoscaler) repo, and you install its CRDs, RBAC and three components yourself:

- **Recommender**: watches Pods' historical usage and computes recommended requests.
- **Updater**: evicts Pods whose requests are too far from the recommendation.
- **Admission Controller**: when a Pod is recreated, a webhook writes the recommended values into the new Pod's requests.

Everything below runs on `k8s-cp1`.

#### 1. Check the Prerequisites

VPA's Recommender also gets usage from metrics-server, so metrics-server from above must be installed and `k top pods` must return numbers. The install script also uses `openssl` to generate the certificate for the Admission Controller webhook:

```bash
k top nodes
openssl version
```

<!-- screenshot: output of k top nodes and openssl version -->

#### 2. Clone the autoscaler Repo and Check Out a VPA Release

Manifests on `master` may reference images that haven't been released yet, so check out the latest VPA release tag first:

```bash
cd ~
git clone https://github.com/kubernetes/autoscaler.git
cd autoscaler/vertical-pod-autoscaler

# List the latest VPA release, then check it out
git tag -l 'vertical-pod-autoscaler-*' | sort -V | tail -1
git checkout <tag printed above>
```

#### 3. Run vpa-up.sh

`vpa-up.sh` applies the CRDs and RBAC first and then deploys the three components, so there's no need to `k apply` the CRDs and RBAC separately:

```bash
./hack/vpa-up.sh
```

<!-- screenshot: vpa-up.sh output -->

#### 4. Verify the Installation

Kubernetes only recognizes the `VerticalPodAutoscaler` resource once the CRDs are registered:

```bash
k get crd | grep verticalpodautoscaler
# verticalpodautoscalercheckpoints.autoscaling.k8s.io
# verticalpodautoscalers.autoscaling.k8s.io

k get pods -n kube-system | grep vpa
# vpa-admission-controller-xxx   1/1   Running
# vpa-recommender-xxx            1/1   Running
# vpa-updater-xxx                1/1   Running
```

<!-- screenshot: CRDs and all three VPA Pods Running -->

To remove it later, run `./hack/vpa-down.sh` from the same directory.

Then create a VPA object pointing at the Deployment to tune:

```yaml
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
  name: php-apache-vpa
spec:
  targetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: php-apache
  updatePolicy:
    updateMode: "Off"
  resourcePolicy:
    containerPolicies:
    - containerName: "*"
      minAllowed:
        cpu: 100m
        memory: 64Mi
      maxAllowed:
        cpu: "1"
        memory: 512Mi
```

`updateMode` decides whether VPA actually acts:

| updateMode | Behavior |
|--|--|
| `Off` | Only computes recommendations and changes nothing; good for observing first |
| `Initial` | Applies recommendations only when Pods are created, never afterwards |
| `Recreate` | Evicts Pods when they drift too far and applies the new values on recreation |
| `InPlaceOrRecreate` | Prefers resizing resources in place (no Pod restart) and falls back to eviction; requires a newer VPA release |

`Auto` also shows up a lot in older docs. It currently behaves like `Recreate` and is no longer recommended.

After it runs for a while, you can see VPA's recommendation:

```bash
k describe vpa php-apache-vpa
```

In the `Recommendation` block of the output, `Target` is the suggested value, and `Lower Bound` / `Upper Bound` give the reasonable range.

>[!WARNING] Don't let HPA and VPA both act on CPU / memory
>HPA adds and removes replicas based on CPU utilization, while VPA adjusts requests based on CPU usage, and the two fight each other: VPA raises requests, utilization drops, and HPA scales down. If you use both, have HPA watch a custom metric (such as requests per second), or run VPA in `Off` mode purely as a reference for setting requests.

---

That covers most of Workloads & Scheduling. The next post moves on to Kubernetes networking: Services, DNS, NetworkPolicy, and the Gateway API, which was also added in the 2025 revision.

---

References:

[1] Deployments - https://kubernetes.io/docs/concepts/workloads/controllers/deployment/

[2] ConfigMaps - https://kubernetes.io/docs/concepts/configuration/configmap/

[3] Secrets - https://kubernetes.io/docs/concepts/configuration/secret/

[4] Resource Management for Pods and Containers - https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/

[5] Limit Ranges - https://kubernetes.io/docs/concepts/policy/limit-range/

[6] Resource Quotas - https://kubernetes.io/docs/concepts/policy/resource-quotas/

[7] Assigning Pods to Nodes - https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/

[8] Taints and Tolerations - https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/

[9] DaemonSet - https://kubernetes.io/docs/concepts/workloads/controllers/daemonset/

[10] Create static Pods - https://kubernetes.io/docs/tasks/configure-pod-container/static-pod/

[11] Horizontal Pod Autoscaling - https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/

[12] HorizontalPodAutoscaler Walkthrough - https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale-walkthrough/

[13] metrics-server - https://github.com/kubernetes-sigs/metrics-server

[14] Vertical Pod Autoscaler - https://github.com/kubernetes/autoscaler/tree/master/vertical-pod-autoscaler
