Skip to main content

Containers and Kubernetes · Intermediate · 20 min

Set CPU and memory requests and limits in Kubernetes

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Kubernetes 1.37 · kind 0.33 · kubeconform 0.8.0

You will give a Kubernetes 1.37 workload sized CPU and memory requests and limits, watch a memory limit kill a pod and a CPU limit throttle one, give a namespace default sizes and a quota, and resize a running pod without restarting it.

On this page

Every container in Kubernetes can carry two numbers per resource. A request is what the scheduler reserves for the container when it picks a node: a pod only lands on a node with enough unreserved CPU and memory to cover its requests. A limit is a ceiling that the kubelet and the Linux kernel enforce while the container runs. The two behave very differently once a container hits them: going over a CPU limit makes the container slow, going over a memory limit gets it killed.

Leave both out and your pods still run, but the scheduler packs them blind, one runaway process can starve its neighbours, and an autoscaler has nothing to measure against. In this tutorial you write manifests with sensible numbers, then break them on purpose on a kind cluster so you can recognise each failure when it happens on a cluster you care about.

Everything lives in ~/resources-demo on your machine and in a namespace called resources-demo on the cluster, so clean-up at the end is two commands.

Step 1 · Install kubeconform and make a demo folder

kubeconform checks manifests against the Kubernetes API schemas before they reach a cluster. That catches typos such as memroy: or a limit in the wrong place, which kubectl apply would otherwise reject one file at a time. Install the 0.8.0 release:

Bash
ARCH="$(dpkg --print-architecture)"
curl -fsSL "https://github.com/yannh/kubeconform/releases/download/v0.8.0/kubeconform-linux-${ARCH}.tar.gz" -o /tmp/kubeconform.tar.gz
sudo tar -xzf /tmp/kubeconform.tar.gz -C /usr/local/bin kubeconform
rm /tmp/kubeconform.tar.gz
kubeconform -v
mkdir -p ~/resources-demo

On macOS, brew install kubeconform does the same. A binary installed by hand gets no updates from apt; to upgrade, run the same commands with the newer version number from the project's releases page.

Create the namespace on your cluster:

Bash
cat > ~/resources-demo/namespace.yaml <<'YAML'
apiVersion: v1
kind: Namespace
metadata:
  name: resources-demo
YAML
Bash
kubectl apply -f ~/resources-demo/namespace.yaml

Check it worked

kubeconform -v prints v0.8.0, and kubectl get namespace resources-demo shows the namespace as Active.

Step 2 · Write a Deployment with requests and limits

CPU is counted in cores, and m means thousandths of a core: 250m is a quarter of one CPU. Memory is counted in bytes, and Mi and Gi are powers of two (128Mi is 128 × 1024 × 1024 bytes). Watch the case: 128M is a smaller decimal megabyte figure, and 128m of memory would mean 0.128 bytes.

Write a small web Deployment with all four values set:

Bash
cat > ~/resources-demo/web.yaml <<'YAML'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
  namespace: resources-demo
spec:
  replicas: 2
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
        - name: web
          image: nginx:1.30-alpine
          ports:
            - containerPort: 80
          resources:
            requests:
              cpu: 100m
              memory: 64Mi
            limits:
              cpu: 500m
              memory: 128Mi
YAML
kubeconform -strict -summary -kubernetes-version 1.37.3 ~/resources-demo/web.yaml

Read the block as two promises. The requests say "do not put this pod on a node unless 100m of CPU and 64Mi of memory are still unreserved there". The limits say "never let it use more than half a core, and kill it if it goes past 128Mi". Note that the scheduler only looks at requests, never at actual use: a node can be idle and still refuse a pod because its requests are all taken.

Apply it:

Bash
kubectl apply -f ~/resources-demo/web.yaml
kubectl rollout status deployment/web -n resources-demo

Check it worked

kubeconform prints a summary with Valid: 1, Invalid: 0. Then look at the node's books:

Bash
kubectl describe node kind-control-plane | grep -A8 'Allocated resources'

Replace kind-control-plane with your node name from kubectl get nodes if your cluster has another name. The table shows CPU and memory requests and limits as totals and percentages of what the node can allocate. Delete the Deployment and run the command again: the CPU requests total drops by 200m, because two replicas each reserved 100m. Apply it again before you carry on.

Step 3 · Watch a memory limit kill a pod

Memory cannot be slowed down the way CPU can. When a container's processes try to go past the memory limit, the kernel's out-of-memory (OOM) killer stops a process in that container. Kubernetes records this as OOMKilled with exit code 137 (128 plus signal 9, SIGKILL).

This pod asks Python to build a 300 MiB string inside a 128Mi limit:

Bash
cat > ~/resources-demo/memhog.yaml <<'YAML'
apiVersion: v1
kind: Pod
metadata:
  name: memhog
  namespace: resources-demo
spec:
  restartPolicy: Never
  containers:
    - name: memhog
      image: python:3.15-slim
      command: ["python3", "-c", "data = b'x' * (300 * 1024 * 1024); print('allocated'); import time; time.sleep(3600)"]
      resources:
        requests:
          cpu: 100m
          memory: 64Mi
        limits:
          memory: 128Mi
YAML
kubeconform -strict -summary -kubernetes-version 1.37.3 ~/resources-demo/memhog.yaml

b'x' * n writes every byte, so the memory is really used, not just reserved. restartPolicy: Never keeps the dead pod around for you to inspect; under a Deployment the kubelet would restart it and you would see CrashLoopBackOff instead.

Bash
kubectl apply -f ~/resources-demo/memhog.yaml
kubectl get pod memhog -n resources-demo --watch

The image takes a moment to pull. Press Ctrl+C when the status changes.

Check it worked

The STATUS column shows OOMKilled, and the word allocated never appears in kubectl logs memhog -n resources-demo. Confirm the reason and exit code:

Bash
kubectl get pod memhog -n resources-demo \
  -o jsonpath='{.status.containerStatuses[0].state.terminated.reason} {.status.containerStatuses[0].state.terminated.exitCode}{"\n"}'

It prints OOMKilled 137. When you meet exit code 137 on a real workload, compare the limit with what the app needs at its peak, not its average. Delete the pod:

Bash
kubectl delete pod memhog -n resources-demo

Step 4 · Watch a CPU limit throttle a pod

A CPU limit is enforced by the kernel's CPU scheduler. In each 100 ms period, a container with a 200m limit may run for 20 ms of CPU time in total; after that its threads wait for the next period. Nothing is killed. The app just gets slower, which on a web service shows up as higher response times, not as errors.

This pod spins one busy loop against a 200m limit:

Bash
cat > ~/resources-demo/cpuhog.yaml <<'YAML'
apiVersion: v1
kind: Pod
metadata:
  name: cpuhog
  namespace: resources-demo
spec:
  containers:
    - name: cpuhog
      image: busybox:1.37
      command: ["sh", "-c", "while true; do :; done"]
      resources:
        requests:
          cpu: 100m
          memory: 16Mi
        limits:
          cpu: 200m
          memory: 32Mi
YAML
kubeconform -strict -summary -kubernetes-version 1.37.3 ~/resources-demo/cpuhog.yaml
Bash
kubectl apply -f ~/resources-demo/cpuhog.yaml
kubectl wait --for=condition=Ready pod/cpuhog -n resources-demo --timeout=60s

To measure usage, kubectl top needs metrics-server, which kind does not install. Install release 0.9.1 and add --kubelet-insecure-tls, because kind's kubelets use self-signed certificates. Use that flag only on a cluster on your own laptop, never on a shared one. If metrics-server is already running, for example from /tutorials/scale-snip-with-a-horizontal-pod-autoscaler (check with kubectl get deployment metrics-server -n kube-system), skip these three commands and the metrics-server delete at the end:

Bash
kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/download/v0.9.1/components.yaml
kubectl patch deployment metrics-server -n kube-system --type=json \
  -p '[{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--kubelet-insecure-tls"}]'
kubectl rollout status deployment/metrics-server -n kube-system --timeout=120s

Wait about a minute for the first samples, then:

Bash
kubectl top pod cpuhog -n resources-demo
kubectl exec cpuhog -n resources-demo -- cat /sys/fs/cgroup/cpu.stat

Check it worked

kubectl top shows the pod at about 200m of CPU, even though the loop would happily use a whole core. In the cpu.stat output (on a node with cgroup v2, which current Docker and kind use), nr_throttled counts the periods in which the container hit its limit and throttled_usec the total time it waited. Run the cat again a few seconds later: both numbers keep growing. Leave cpuhog running for the next step.

Should you set CPU limits at all?

This is one of the few real arguments in Kubernetes sizing, and both sides have a point.

  • Against CPU limits: throttling happens even when the node has idle CPU, so a limit can make an app slow for no benefit. A short burst, such as a Java app starting up or a request that fans out to many threads, can use a period's quota in a few milliseconds and then stall. Requests already guarantee each pod its share when CPU is contested, because the kernel weighs CPU time by request.
  • For CPU limits: without them a busy pod uses any spare CPU, so its speed depends on its neighbours and drops when they get busy, which makes load tests misleading. On clusters shared between teams or customers, limits stop one tenant borrowing everyone else's headroom. And a pod is only in the Guaranteed class (next step) if its CPU limit equals its request.

A common middle path: always set CPU requests, always set memory limits, and add CPU limits where you need predictability or tenant isolation. If you leave them off, watch nr_throttled and response times instead of guessing.

Step 5 · Read the QoS class Kubernetes gives each pod

From the requests and limits you set, Kubernetes puts every pod in one of three quality of service (QoS) classes. You never set the class directly.

  • Guaranteed: every container has CPU and memory limits, and each request equals its limit.
  • Burstable: at least one container has a CPU or memory request or limit, but the pod does not meet the Guaranteed rule.
  • BestEffort: no container has any request or limit.

The class matters when a node runs short of memory. The kubelet then evicts pods to protect the node: first pods using more than they request, ordered by pod priority and then by how far over their request they are. BestEffort pods request nothing, so any use at all is above their request and they go first; Guaranteed pods that stay within their requests go last. The kernel's OOM killer, if it gets there first, follows a similar order.

Write one pod of each class:

Bash
cat > ~/resources-demo/qos.yaml <<'YAML'
apiVersion: v1
kind: Pod
metadata:
  name: qos-guaranteed
  namespace: resources-demo
spec:
  containers:
    - name: app
      image: busybox:1.37
      command: ["sleep", "3600"]
      resources:
        requests:
          cpu: 50m
          memory: 32Mi
        limits:
          cpu: 50m
          memory: 32Mi
---
apiVersion: v1
kind: Pod
metadata:
  name: qos-burstable
  namespace: resources-demo
spec:
  containers:
    - name: app
      image: busybox:1.37
      command: ["sleep", "3600"]
      resources:
        requests:
          cpu: 50m
          memory: 32Mi
---
apiVersion: v1
kind: Pod
metadata:
  name: qos-besteffort
  namespace: resources-demo
spec:
  containers:
    - name: app
      image: busybox:1.37
      command: ["sleep", "3600"]
YAML
kubeconform -strict -summary -kubernetes-version 1.37.3 ~/resources-demo/qos.yaml
Bash
kubectl apply -f ~/resources-demo/qos.yaml
kubectl get pods -n resources-demo -o custom-columns=NAME:.metadata.name,QOS:.status.qosClass

Check it worked

The table lists qos-guaranteed as Guaranteed, qos-burstable as Burstable and qos-besteffort as BestEffort. The web pods and cpuhog are Burstable, because their requests are lower than their limits. Delete the three QoS pods before the next step, because the quota you are about to add would count them:

Bash
kubectl delete -f ~/resources-demo/qos.yaml
kubectl delete pod cpuhog -n resources-demo

Step 6 · Give the namespace defaults and a quota

Requests only work if people set them. Two namespace objects make that the default rather than a code review comment.

A LimitRange fills in requests and limits for containers that leave them out, and rejects containers outside a minimum and maximum. A ResourceQuota caps the total that all pods in the namespace may request and use. Once a quota covers requests.cpu or limits.memory, any pod that does not state those values is rejected, so the two objects work as a pair: the LimitRange supplies values, the quota adds them up.

Bash
cat > ~/resources-demo/namespace-policy.yaml <<'YAML'
apiVersion: v1
kind: LimitRange
metadata:
  name: container-defaults
  namespace: resources-demo
spec:
  limits:
    - type: Container
      defaultRequest:
        cpu: 100m
        memory: 64Mi
      default:
        memory: 128Mi
      max:
        memory: 512Mi
---
apiVersion: v1
kind: ResourceQuota
metadata:
  name: team-budget
  namespace: resources-demo
spec:
  hard:
    requests.cpu: "1"
    requests.memory: 1Gi
    limits.memory: 2Gi
    pods: "10"
YAML
kubeconform -strict -summary -kubernetes-version 1.37.3 ~/resources-demo/namespace-policy.yaml

The LimitRange sets no default CPU limit, in line with the middle path above, but it does give every container a memory limit. That is also why its max lists only memory: when a LimitRange has a max for a resource but no default, the API server copies the max in as the default limit, so a CPU max here would quietly become every container's CPU limit. The quota leaves out limits.cpu for the same reason: if it covered CPU limits, every pod would have to set one.

Then write a pod with no resources block and one that asks for more than the maximum:

Bash
cat > ~/resources-demo/policy-check.yaml <<'YAML'
apiVersion: v1
kind: Pod
metadata:
  name: no-resources
  namespace: resources-demo
spec:
  containers:
    - name: app
      image: busybox:1.37
      command: ["sleep", "3600"]
---
apiVersion: v1
kind: Pod
metadata:
  name: too-big
  namespace: resources-demo
spec:
  containers:
    - name: app
      image: busybox:1.37
      command: ["sleep", "3600"]
      resources:
        requests:
          memory: 1Gi
        limits:
          memory: 1Gi
YAML
kubeconform -strict -summary -kubernetes-version 1.37.3 ~/resources-demo/policy-check.yaml

Both pods are valid Kubernetes objects, which is why kubeconform accepts them. The policy is checked by the API server when you apply:

Bash
kubectl apply -f ~/resources-demo/namespace-policy.yaml
kubectl apply -f ~/resources-demo/policy-check.yaml

Check it worked

The second apply creates no-resources and refuses too-big with a Forbidden error naming the 512Mi maximum. Check what the defaults filled in:

Bash
kubectl get pod no-resources -n resources-demo -o jsonpath='{.spec.containers[0].resources}{"\n"}'
kubectl describe resourcequota team-budget -n resources-demo

The first command shows requests of 100m and 64Mi and a memory limit of 128Mi, with no CPU limit, none of which you wrote. kubectl get limitrange container-defaults -n resources-demo -o yaml shows the stored object as the API server filled it in. The quota shows Used against Hard for each line; the web pods, which were created before the quota existed, are counted too. Defaults only apply to new pods, so a LimitRange never changes pods that are already running. Delete the test pod:

Bash
kubectl delete pod no-resources -n resources-demo

Step 7 · Resize a running pod in place

Changing a Deployment's resources rolls out new pods. Since Kubernetes 1.35 you can also resize a running pod's CPU and memory without recreating it, through the pod's resize subresource; it is stable and on by default in 1.37. resizePolicy says, per resource, whether the container may be resized live (NotRequired, the default) or must restart to pick up the change (RestartContainer). Many runtimes, such as the JVM with a fixed heap, only read their memory size at start, so they need the restart for memory.

Bash
cat > ~/resources-demo/resizable.yaml <<'YAML'
apiVersion: v1
kind: Pod
metadata:
  name: resizable
  namespace: resources-demo
spec:
  containers:
    - name: app
      image: busybox:1.37
      command: ["sleep", "3600"]
      resizePolicy:
        - resourceName: cpu
          restartPolicy: NotRequired
        - resourceName: memory
          restartPolicy: RestartContainer
      resources:
        requests:
          cpu: 100m
          memory: 64Mi
        limits:
          cpu: 200m
          memory: 128Mi
YAML
kubeconform -strict -summary -kubernetes-version 1.37.3 ~/resources-demo/resizable.yaml
Bash
kubectl apply -f ~/resources-demo/resizable.yaml
kubectl wait --for=condition=Ready pod/resizable -n resources-demo --timeout=60s
kubectl patch pod resizable -n resources-demo --subresource resize --patch \
  '{"spec":{"containers":[{"name":"app","resources":{"requests":{"cpu":"200m"},"limits":{"cpu":"400m"}}}]}}'

The --subresource resize flag needs kubectl 1.32 or later. The rules that apply: only CPU and memory can be resized, a request or limit cannot be removed, and the QoS class cannot change, so this Burstable pod must keep its requests below its limits. If the node cannot fit the new size, the pod gets a PodResizePending condition with reason Deferred (may fit later) or Infeasible (never will) and keeps its old size.

Check it worked

Bash
kubectl get pod resizable -n resources-demo \
  -o jsonpath='{.status.containerStatuses[0].resources}{"  restarts="}{.status.containerStatuses[0].restartCount}{"\n"}'

The status shows cpu: 200m requested and cpu: 400m as the limit, and restarts=0. spec holds what you asked for; status holds what the kubelet has applied, so a mismatch between them means the resize is still in progress or pending. A resized pod that belongs to a Deployment goes back to the template's values when it is replaced, so put the new numbers in the manifest too.

Step 8 · Size requests from measured usage, then clean up

The numbers so far were picked for the demos. For your own apps, measure first. Run the app under realistic traffic, ideally over a full busy day, and read usage per container:

Bash
kubectl top pod -n resources-demo --containers

kubectl top shows a recent sample, not history, so take readings at quiet and busy times, or read the same figures from your monitoring if you have it. Then:

  • CPU request: about what the container uses on a normal busy period. Too low and the pod is starved when the node is contested; too high and you pay for reserved CPU that sits idle.
  • Memory request: the steady usage at the busy period, since memory is rarely given back.
  • Memory limit: the highest usage you saw plus headroom, such as 25%. Setting it equal to the request gives the most predictable behaviour; a gap allows bursts but makes the pod an earlier eviction candidate.
  • CPU limit: per the trade-off above. If you set one, check nr_throttled after the change.

Write the result into the manifest and review it every few releases, because usage changes with the code. Tight requests matter most where every node is paid for out of a fixed budget, such as a small cluster on prepaid cloud credit: over-sized requests leave nodes looking full while their CPUs idle.

When you are done, the following deletes the namespace and every object in it, including the Deployment, the quota and the resizable pod. It also removes metrics-server, which you added in this tutorial; leave out that second line if metrics-server was running before you started. Last, it removes the kubeconform binary you installed by hand; skip that line if you are moving on to another Kubernetes tutorial that uses it, such as /tutorials/validate-kubernetes-manifests-before-they-reach-a-cluster. Make sure you have not put anything else in the resources-demo namespace before you run it:

Bash
kubectl delete namespace resources-demo
kubectl delete -f https://github.com/kubernetes-sigs/metrics-server/releases/download/v0.9.1/components.yaml
sudo rm /usr/local/bin/kubeconform
Bash
rm -r ~/resources-demo

Check it worked

kubectl get namespace resources-demo reports NotFound once deletion finishes, kubectl get deployment metrics-server -n kube-system reports NotFound (unless you kept an earlier install), command -v kubeconform prints nothing, and ~/resources-demo is gone. Keep the kind cluster if you are moving on to another Kubernetes tutorial; otherwise remove it with kind delete cluster.

Next steps

  • Make an autoscaler use the requests you set, since HPA utilisation is a share of the request: /tutorials/scale-snip-with-a-horizontal-pod-autoscaler.
  • Find out why a pod is Pending, OOMKilled or in CrashLoopBackOff: /tutorials/debug-a-failing-kubernetes-pod-with-kubectl.
  • Apply the same CPU and memory ideas to a plain Linux service with cgroups: /tutorials/limit-a-service-cpu-and-memory-with-systemd.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.