Limit Range

By default, containers run with unbounded compute resources on a Kubernetes cluster.

LimitRange is a Kubernetes resource that enforces resource constraints (CPU, memory) at the namespace level. It ensures that every pod/container in the namespace has a default resource request and limit. Containers cannot exceed the specified limits. Using this will prevents excessive resource consumption by a single pod/container.

Define LimitRange

Lets create new file limitrange.yaml and put below definition there. This configuration will limit CPU and Memory in container level.

apiVersion: v1
kind: LimitRange
metadata:
  name: resource-limits
  namespace: limited
spec:
  limits:
  - type: Container
    defaultRequest:
      cpu: "100m"
      memory: "64Mi"
    default:
      cpu: "100m"
      memory: "64Mi"
    max:
      cpu: "250m"
      memory: "128Mi"
  • defaultRequest: Define the default request for each containers.

    • cpu: "100m": Set container's resource.request.cpu to 100m if not explicitly specified.

    • memory: "64Mi": Set container's resource.request.memory to 64Mi if not explicitly specified.

  • default: Define the default limit for each containers.

    • cpu: "100m": Set container's resource.limits.cpu to 100m if not explicitly specified.

    • memory: "64Mi": Set container's resource.limits.memory to 64Mi if not explicitly specified.

  • max: Define the default request for each containers. The limits for configured in each containers cannot exceed this value.

Apply and Validate

Let's apply the configuration file using kubectl apply command.

We can validate it using kubectl describe limitranges command with specific namespace.

Test LimitRange

To test if our configuration work as expected we can run pod without any resource specified.

Lets get the pod details using kubectl describe command.

As you can see above if we don't specify the resource.request and resource.limits it will set to default that we just configure.

Now let's try to create a new pod that will exceed the max configuration of our LimitRange. Create new file named limitrange-pod.yaml and put below definition there.

Lets apply and see what happens.

As you can see we got error creating pods "over-limit-pod" is forbidden because the CPU and Memory limits exceed the LimitRange.

References

Last updated