Namespaces in Kubernetes act as a layer of isolation and organization for cluster resources. They allow you to segregate workloads, control resource allocation, and manage access to resources.

Why Use Namespaces?

  1. Isolation: Separate teams or projects can work without interfering with each other.
  2. Resource Management: Apply resource quotas to control CPU, memory, and storage usage.
  3. Access Control: Fine-grained permission control at the namespace level.
  4. Organization: Easier to manage resources by categorizing them into namespaces.

Creating and Managing Namespaces

Create a Namespace

To create a namespace, you can use the kubectl command:

kubectl create namespace my-namespace

Note: Use ns as short

List Namespaces

To list all namespaces:

kubectl get namespaces

Delete a Namespace

To delete a namespace:

kubectl delete namespace my-namespace

Resource Quotas per Namespace

You can set resource quotas to limit resources within a namespace.

Create a Resource Quota

Create a YAML file named resource-quota.yaml:

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

Apply the resource quota to a namespace:

kubectl apply -f resource-quota.yaml -n my-namespace

Note: Check LimitRanges as well.

Best Practices

  1. Standardize Naming: Stick to a naming convention for easier management.
  2. Limit Resource Allocation: Always set resource quotas to avoid resource exhaustion.
  3. Use RBAC: Implement Role-Based Access Control for secure access.
  4. Documentation: Document the purpose and policies for each namespace.

Exercise: Namespace and Resource Quota Setup

Setup

  1. Install Kubernetes and kubectl.
  2. Access to a running cluster.

Steps

  1. Create a namespace: kubectl create namespace exercise-ns
  2. Create a Resource Quota YAML file.
  3. Apply the Resource Quota to exercise-ns.

Troubleshooting

  1. Namespace not found: Make sure you specify the correct namespace in your kubectl commands.
  2. Resource Quota not applying: Ensure the YAML is correctly formatted and applied to the correct namespace.

Solution

  1. Verify the namespace: kubectl get namespaces
  2. Verify the Resource Quota: kubectl get resourcequota -n exercise-ns