Namespaces

Namespace introduction

In this section, we will learn about Namespaces.

In the EKS workshops, we would have to create objects like Pods, Deployments and Services in our cluster. All said objects, was in the same namespace.

The default Namespace in Kubernetes is the one automatically created when Kubernetes is initialized and configured.

Command

You can use the following command to list all namespaces in your cluster:

kubectl get namespaces

You can create your own namespace:

kubectl create namespace dev

To list all pods in the default namespace:

kubectl get pods

To list all pods in a non-default namespace:

kubectl get pods --namespace=kube-system

* Replace kube-system with a namespace you wish to check

When creating a pod with the manifest file, without the namespace field, the pod will be created in the default namespace:

apiVersion: v1
kind: Pod
metadata:
  name: myapp-pod
  labels:
     app: myapp
     type: front-end
spec:
  containers:
  - name: nginx-container
    image: nginx
kubectl create -f pod-definition.yaml

To create a Pod with the same Pod definition file in a different namespace, use the --namespace option.

kubectl create -f pod-definition.yaml --namespace=dev

If you want to ensure that this Pod is always created in the dev environment, even when not specified in the command line, you can move the --namespace definition into the Pod definition file.

apiVersion: v1
kind: Namespace
metadata:
  name: dev
kubectl create -f namespace-dev.yaml

Or use the shorter command:

kubectl create namespace dev

By default, we will be in a default namespace. To switch to a specific namespace permanently, run the following command:

kubectl config set-context $(kubectl config current-context) --namespace=dev

To list all Pods in all namespaces:

kubectl get pods --all-namespaces

To limit resources within a namespace, create a resource quota. To create one, start with the ResourceQuota definition file.

apiVersion: v1
kind: ResourceQuota
metadata:
  name: compute-quota
  namespace: dev
spec:
  hard:
    pods: "10"
    requests.cpu: "4"
    requests.memory: 5Gi
    limits.cpu: "10"
    limits.memory: 10Gi
kubectl create -f compute-quota.yaml

References