Namespaces in Kubernetes
A default namespace is created automatically when the cluster is being setup. To isolate or prevent a user from accidentally deleting the services, Kubernetes creates certain pods for its internal purpose like networking solution, DNS service etc.
Kubernetes creates them under another namespace which is created at cluster startup named kube-system. The third namespace that is created automatically called kube-public is where resources available to all users are created.
If an environment is small or if a user is playing around the cluster(learning), then the user doesn’t really have to worry about namespace. The user can hold up the work in default namespace. However, while using Kubernetes for Enterprise or Production, you may have to consider the use of namespaces.
For example, if the same cluster is used for production, dev and test environments and at the same time the resources between them is required to be isolated, in such cases, a separate namespace for each of them can be created in a way such that the resources in other environment should be deleted accidentally.
Each of these namespaces has its own set of policies defined as to who can do what. A quota of resources can also be assigned to each of these namespaces. This way, each of the namespace is guaranteed a certain amount of resources and it won’t use more than the specified quota.
The resources within a namespace can be referred to each other by their respective names
In the above diagram, the WebApp-pod can reach the DB-service by using the host name mysql.connect(“db-service”)
If the WebApp-pod is supposed to reach DB-service in dev namespace, the name of the namespace must be appended to the name of the service as given in the below format:
Now, this can be seen and accessed. This is because, a DNS entry is added automatically in this format when the service is created.
Operational aspects of Namespaces
- To list the pods in default name, execute the following command
kubectl get pods or kubectl get pods -n default
- To the list the pods in kube-system namespace, execute
kubectl get pods -n kube-system
- To create a pod in a particular namespace (dev), execute
kubectl create -f sample-pod.yml –namespace dev
Add the namespace string under metadata section of pod definition in the yaml file.
- To create a namespace, use either a yaml file given below which is similar to the one that is used for any object
Execute the following command:
kubectl create namespace dev
- In order to switch to the dev namespace permanently without specifying the namespace every time for dev, use the following command:
kubectl config set-context $(kubectl config current-context) –namespace=dev
- To view pods in all namespaces, use the following command
kubectl get pods --all-namespaces
- To limit the resources in a namespace, use resource quota which is given below