Kubernetes resource quotas and limits are essential for managing cluster resources effectively. They enable administrators to allocate specific amounts of resources per namespace, and developers to specify resource requirements for their Pods.

Overview of Resource Quotas

Resource quotas are set on a per-namespace basis to restrict the amount of resources that can be consumed in that namespace. It controls aspects like CPU, memory, storage, and even object count (like Pods, Services, etc.) within the namespace.

apiVersion: v1
kind: ResourceQuota
metadata:
  name: my-quota
spec:
  hard:
    pods: "10"
    requests.cpu: "1"
    requests.memory: 1Gi
    limits.cpu: "2"
    limits.memory: 2Gi

Setting Resource Quotas

  1. Create a YAML File: Create a file named my-quota.yaml and copy the above YAML into it.

  2. Apply the Quota: Use the kubectl command to apply the resource quota to a specific namespace.

    kubectl apply -f my-quota.yaml --namespace=<your-namespace>
    

Working with LimitRange

LimitRange sets default, min, and max resource limits for Pods and Containers in a namespace. When no resource requests/limits are specified, the LimitRange defaults apply.

apiVersion: v1
kind: LimitRange
metadata:
  name: my-limit-range
spec:
  limits:
  - default:
      cpu: "500m"
      memory: "512Mi"
    defaultRequest:
      cpu: "200m"
      memory: "256Mi"
    type: Container
  1. Create a YAML File: Create a file named my-limit-range.yaml.

  2. Apply the LimitRange:

    kubectl apply -f my-limit-range.yaml --namespace=<your-namespace>
    

Monitoring and Enforcement

Use kubectl describe to monitor resource quota and limit ranges.

  • Resource Quota:

    kubectl describe resourcequota my-quota --namespace=<your-namespace>
    
  • LimitRange:

    kubectl describe limitrange my-limit-range --namespace=<your-namespace>
    

Best Practices

  • Be Conservative: Start with conservative resource quotas and adjust as needed.
  • Resource Types: Don’t just limit CPU and memory; consider other resource types like persistent volume claims (PVCs).
  • Namespace Defaults: Use LimitRange to set sensible defaults for namespaces so that developers don’t have to specify them every time.

To try all of these out, you can:

Setup:

  1. Install Minikube or set up a Kubernetes cluster.
  2. Create a new namespace.

Steps:

  1. Apply the ResourceQuota and LimitRange YAML files.
  2. Monitor them using kubectl describe.

Troubleshooting:

  • Make sure you are in the correct namespace when applying and describing resources.
  • Use kubectl get events --sort-by='.metadata.creationTimestamp' to see recent events, including quota violations.

Solution:

By following this guide, you should have a working ResourceQuota and LimitRange setup in your namespace, allowing for better resource management and allocation.