How to implement namespace quotas in Kubernetes


Namespaces allow us to organize and isolate our Kubernetes objects. Kubernetes is an open-source orchestration system that allows us to deploy, scale, and manage our Kubernetes clusters.

Namespace quotas

In Kubernetes, we can use the Kubernetes ResourceQuota object to allocate namespace quotas to a namespace or objects. We can use this object to limit the amount of CPU, memory, storage, and objects created in a specific namespace. Namespace quotas are useful when we have many objects and want to ensure that the resources to different clusters or resources within a cluster are evenly distributed or distributed according to a certain ratio.

Example

Let’s have a look at an executable. In the following example, we’re creating a kind cluster of one node.

# Create a namespace 
apiVersion: v1
kind: Namespace
metadata:
  name: educative-namespace

---

# Create a ResourceQuota

apiVersion: v1
kind: ResourceQuota
metadata:
  name: resourcequota-demo
  namespace: educative-namespace
spec:
  hard:
    requests.cpu: "1"
    requests.memory: 1Gi
    limits.cpu: "2"
    limits.memory: 2Gi
Allocating resource quotas to a namespace

In the above example, the resource-namespace.yaml file contains the definitions of two Kubernetes objects, a namespace, and ResourceQuota.

Explanation

Lines 2 and 11: We define the Kubernetes API version that we’ll use to create the namespace and the ResourceQuota objects, i.e., v1.

Lines 3 and 12: We define the types of objects that will be created, i.e., ResourceQuota and a namespace object.

Lines 5 and 14: We give a name to the objects that will be created using their respective definitions, i.e., educative-namespace and educative-resourcequota.

Line 15: We specify the namespace for this ResourceQuota.

Lines 16–20: We allocate the resources and specify the requirements for this namespace. All containers in every pod created in this namespace must have a memory request, memory limit, CPU request, and CPU limit.

  • The memory and CPU requests must not exceed 1 GiB and 1 CPU for all pods created in this namespace.

  • The total memory and CPU limit must not exceed 2 GiB and 2 CPUs for all pods created in this namespace.

To create the namespace and the ResourceQuota object, use the following commands:

kubectl apply -f resource-namespace.yaml

If you want to check the status of resources, execute the following command:

kubectl get namespace,resourcequota --all-namespaces

You can create pods and deployments in this namespace and try different namespaces.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved