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?
- Isolation: Separate teams or projects can work without interfering with each other.
- Resource Management: Apply resource quotas to control CPU, memory, and storage usage.
- Access Control: Fine-grained permission control at the namespace level.
- 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
- Standardize Naming: Stick to a naming convention for easier management.
- Limit Resource Allocation: Always set resource quotas to avoid resource exhaustion.
- Use RBAC: Implement Role-Based Access Control for secure access.
- Documentation: Document the purpose and policies for each namespace.
Exercise: Namespace and Resource Quota Setup
Setup
- Install Kubernetes and
kubectl
. - Access to a running cluster.
Steps
- Create a namespace:
kubectl create namespace exercise-ns
- Create a Resource Quota YAML file.
- Apply the Resource Quota to
exercise-ns
.
Troubleshooting
- Namespace not found: Make sure you specify the correct namespace in your
kubectl
commands. - Resource Quota not applying: Ensure the YAML is correctly formatted and applied to the correct namespace.
Solution
- Verify the namespace:
kubectl get namespaces
- Verify the Resource Quota:
kubectl get resourcequota -n exercise-ns