Kubernetes

How to Work with Namespace Using Kubectl

Kubernetes is a popular container orchestration platform that is widely used by many organizations to manage their containerized applications. One of the key features of Kubernetes is the namespace which allows you to group and isolate the resources within a cluster.

In this article, we will explore what namespaces are; how to create, use, and manage them using Kubectl; and the command-line tool for Kubernetes.

What Is a Namespace in Kubernetes?

A namespace is a virtual cluster that is created within a Kubernetes cluster. It provides a way to divide and isolate the resources within the cluster which allows the different teams or projects to use the same cluster without interfering with each other.

In a namespace, you can create and manage the Kubernetes resources such as pods, services, deployments, and more. Each namespace has its own set of resources and is completely isolated from other namespaces.

Namespaces are often used to organize the resources based on their environment (e.g., production, staging, development), application, team, or any other criteria that makes sense for your organization.

Namespace Types

Kubernetes namespaces come in two types: Kubernetes system namespaces and custom namespaces.

There are four default namespaces that Kubernetes creates automatically.

The first default namespace is called “default” which is a space for objects that don’t have a specified namespace. The second one is called “kube-system” which is the default namespace for Kubernetes system objects such as kube-dns and kube-proxy. It also includes add-ons that provide cluster-level features such as web UI dashboards, ingresses, and cluster-level logging. The third one is called “kube-public” which is a default namespace for resources that are available to all users without authentication. The last one is “kube-node-lease” which is a default space for objects that are related to cluster scaling.

Admins can also create custom Kubernetes namespaces. They can create as many as needed to isolate the workloads or resources and limits the access to specific users. This is particularly useful when multiple teams or projects share the same Kubernetes cluster and wants to separate their resources from each other.

Why You Should Use Multiple Namespaces

Using multiple Kubernetes namespaces can help manage and organize the resources in a Kubernetes cluster. Here are some examples/scenarios to illustrate why you should use multiple Kubernetes namespaces:

Multi-tenant applications: Suppose you have a Kubernetes cluster that hosts multiple applications for different tenants. In this scenario, you can create a separate namespace for each tenant which isolates their resources from other tenants. This separation helps prevent the interference between tenants and makes it easier to manage the resources.

Multiple environments: Suppose you have a Kubernetes cluster that hosts multiple environments such as development, staging, and production. In this scenario, you can create a separate namespace for each environment which isolates the resources for each environment. This separation helps prevent the issues from one environment affecting another and makes it easier to manage the resources for each environment.

Role-based access control: Suppose you have a Kubernetes cluster that is shared by multiple teams. In this scenario, you can create a separate namespace for each team and apply the role-based access control to limit the access to resources. This separation helps prevent an unauthorized access to the resources and makes it easier to manage the resources for each team.

Resource allocation: Suppose you have a Kubernetes cluster with limited resources and you want to ensure that each team or project gets a fair share of resources. In this scenario, you can create a separate namespace for each team or project and apply the resource quotas to limit the amount of CPU, memory, and other resources that can be used by each namespace.

How to Create a Namespace

Creating a namespace in Kubernetes is a straightforward process. You can create a namespace using the kubectl command-line tool or by creating a YAML manifest file.

Here’s how to create a namespace using the kubectl command-line tool:

Open a terminal window and run the following command to create a namespace:

kubectl create namespace <namespace-name>

Replace <namespace-name> with the desired name for your namespace.

For example, if you want to create a namespace named my-namespace, run the following command:

kubectl create namespace my-namespace

Verify that the namespace has been created successfully by running the following command:

kubectl get namespaces

This command lists all the namespaces in your Kubernetes cluster including the one that you just created.

Here’s an example of the output:

Alternatively, you can create a namespace using a YAML manifest file. Here’s an example of a YAML manifest file to create a namespace:

Save the previous content in a file named my-namespace.yaml. Then, run the following command to create the namespace:

kubectl apply -f my-namespace.yaml

The previous command creates a namespace named my-namespace.

Here’s an example of the output:

In summary, creating a namespace in Kubernetes is a simple process that can be done using the kubectl command-line tool or a YAML manifest file. Once created, you can use the namespace to isolate the resources and apply specific configurations to them.

How to Create a Namespace If It Does Not Exist Yet

To create a namespace in Kubernetes only if it does not exist yet, you can use a YAML manifest file with the “kubectl apply” command. If the namespace already exists, the “kubectl apply” command skips the creation step and moves to the next step in the manifest.

Here’s an example YAML manifest file to create a namespace named my-namespace if it does not exist yet:

The previous manifest creates a namespace named my-namespace and a service named my-service in the my-namespace namespace.

To apply the previous manifest and create the namespace only if it does not exist yet, run the following command:

kubectl apply -f my-namespace.yaml

If the namespace already exists, you will see the following output:

If the namespace does not exist, you will see the following output:

In summary, to create a namespace in Kubernetes only if it does not exist yet, you can use a YAML manifest file with the “kubectl apply” command. The manifest should contain the namespace definition followed by the resources to be created in that namespace. If the namespace already exists, the “kubectl” apply command skips the creation step and moves to the next step in the manifest.

How to List All Namespaces

In Kubernetes, you can list all the existing namespaces in a cluster using the “kubectl get namespaces” command. This command displays the name and status of all the namespaces in the cluster.

Here’s an example output of the “kubectl get namespaces” command:

In the previous example, four namespaces are listed: default, kube-node-lease, kube-public, and kube-system.

To get more detailed information about a specific namespace, you can use the “kubectl describe namespace <namespace-name>” command. This command displays an information such as labels, annotations, and resource quotas for the specified namespace.

Here’s an example output of the “kubectl describe namespace default” command:

In the previous example, the “kubectl describe namespace default” command displays the resource quotas for the default namespace.

In summary, to list all namespaces in a Kubernetes cluster, use the “kubectl get namespaces” command. To get more detailed information about a specific namespace, use the “kubectl describe namespace <namespace-name>” command.

How to Use, Set, Switch, Apply or Change the Namespace

In Kubernetes, you can use, set, switch, apply, or change the namespaces using the kubectl command-line tool.

To use a specific namespace for a command, you can use the –namespace flag followed by the namespace name. For example, to get all the pods in the default namespace, you can run the following command:

kubectl get pods --namespace=default

To set a default namespace for all subsequent kubectl commands, you can use the “kubectl config set-context” command. For example, to set the default namespace as the default for all subsequent kubectl commands, you can run the following command:

kubectl config set-context --current --namespace=default

To switch to a different namespace temporarily for a single command, you can use the “kubectl config set-context” command along with the –namespace flag. For example, to switch to the kube-system namespace temporarily for a single command, you can run the following command:

kubectl config set-context --current --namespace=kube-system

To apply or change the namespace of a resource, you can use the “kubectl apply” command along with a YAML file that specifies the new namespace. For example, to apply a deployment YAML file named my-deployment.yaml to the my-namespace namespace, you can run the following command:

kubectl apply -f my-deployment.yaml --namespace=my-namespace

To verify that the namespace has been applied or changed, you can use the “kubectl describe” command along with the resource type and name. For example, to verify the namespace of a deployment named my-deployment, you can run the following command:

kubectl describe deployment my-deployment

In the output of the previous command, you should see the namespace: field which indicates the current namespace of the deployment.

In summary, you can use the –namespace flag to specify a namespace for a single command, use kubectl config set-context to set a default namespace for all subsequent commands, switch to a different namespace temporarily using the kubectl config set-context –namespace, apply or change the namespace of a resource using the kubectl apply, and verify the namespace of a resource using the kubectl describe.

How to Get the Current Namespace

To get the current namespace in Kubernetes, you can use the “kubectl config view” command which displays the current context configuration for the kubectl command-line tool. The context configuration includes the current namespace as well as other settings such as the current cluster and user.

kubectl config view --minify | grep namespace

The previous command uses grep to extract the current namespace from the output of the “kubectl config view” command.

Sample Output:

This output means that the current namespace is default.

As for the “kubectl config view” command, it displays the current context configuration including the cluster, user, and namespace information. Here’s a sample output of the “kubectl config view” command:

Viewing the Resources in a Namespace

When working with Kubernetes, you can view the resources that exist within a specific namespace using the “kubectl get” command with the –namespace flag. This is useful when you want to focus on a particular set of resources within a larger cluster or when you want to see all the resources within a namespace.

Here is an example of how to use the “kubectl get” command with the –namespace flag to view resources within a specific namespace:

kubectl get pods --namespace=my-namespace

In this example, we’re using the “kubectl get” command to retrieve a list of pods in the my-namespace namespace. The output is a table which shows an information about each pod such as its name, status, and age.

Here’s an example output:

This output shows the name, status, and age of each pod in the my-namespace namespace.

You can use the –all-namespaces flag with the “kubectl get” command to view all the resources across all namespaces. For example:

kubectl get pods --all-namespaces

This displays a list of pods in all namespaces, not just the my-namespace namespace.

It’s important to note that if you don’t specify a namespace using the –namespace flag, kubectl uses the default namespace. You can check the current default namespace by running the “kubectl config view” command.

Limiting the Resource Access in a Namespace

Kubernetes namespaces are useful for organizing and isolating the resources within a cluster. One important aspect of this is the ability to limit the access to the resources within a namespace. This can be done using the Kubernetes role-based access control (RBAC) to define specific roles and permissions for the users or groups within a namespace.

Here is an example of how to limit the resource access in a namespace using RBAC:

Define a role that specifies the desired permissions for a given resource. For example, this role allows a user to list all pods in a namespace:

Bind the role to a user or group within the namespace. For example, this binds the pod-reader role to the “my-user” user within the “my-namespace” namespace:

Verify that the user has the expected permissions by running the following command:

kubectl auth can-i list pods --namespace=my-namespace --as=my-user

This command checks whether the “my-user” user has permission to list the pods in the “my-namespace” namespace. If the user has the pod-reader role as defined in the previous steps, the output is “yes”. If not, the output is “no”.

Here’s an example of the output:

In this way, you can use RBAC to limit the resource access within a namespace in Kubernetes, and ensure that the users or groups only have access to the resources that they need.

Configuring the Default Namespace

In Kubernetes, the default namespace is where all the resources exist unless otherwise specified. By default, when a user runs a command without specifying the namespace, Kubernetes looks for the resources in the default namespace. However, it is possible to configure a different namespace as the default namespace, so the users don’t have to specify it every time they run a command.

To set the default namespace, use the “kubectl config set-context” command with the –namespace flag. Here’s an example:

kubectl config set-context --current --namespace=example-namespace

In the previous command, replace example-namespace with the name of the namespace that you want to set as the default.

To verify that the default namespace has been set correctly, you can use the “kubectl config view” command. The output of this command includes a section called “contexts” which lists all the contexts that are currently configured in the kubeconfig file. The current context is indicated with an asterisk (*), and the namespace field of the current context shows the default namespace.

Here’s an example output of “kubectl config view” command with the default namespace which is set to example-namespace:

In the previous output, you can see that the default namespace is set to example-namespace in the contexts section.

How to Copy a Secret to Another Namespace

To copy a secret from one namespace to another in Kubernetes, we can use the “kubectl get secret” and “kubectl create secret” commands.

Here are the steps to copy a secret to another namespace:

First, we need to get the secret that we want to copy in the source namespace using the “kubectl get secret” command. For example, let’s say we want to copy a secret named my-secret from the source-namespace namespace to the destination-namespace namespace:

kubectl get secret my-secret -n source-namespace -o yaml > my-secret.yaml

This command exports the secret my-secret in a YAML format to a file named my-secret.yaml.

Next, we need to modify the metadata section of the YAML file to change the namespace from the source-namespace to the destination-namespace. Open the file in a text editor and change the namespace field as shown in the following:

Finally, we can create the secret in the destination namespace using the modified YAML file using the “kubectl create secret” command:

kubectl create -f my-secret.yaml

This creates the my-secret secret in the destination-namespace namespace.

Sample Output:

Assuming that we want to copy a secret named my-secret from the source-namespace namespace to the destination-namespace namespace, the sample output for the previous commands would be:

How the Namespaces Interact with DNS

Each namespace has a unique name that is used to identify the resources within that namespace. DNS, on the other hand, is used to translate the human-readable domain names into IP addresses that the computers can use to locate the resources on a network.

Kubernetes uses DNS to provide a name resolution for the services within a cluster. Each service gets a DNS name in the <service-name>.<namespace>.svc.cluster.local format. This allows the services within a namespace to be accessed using their DNS name without the need to know their IP address. For example, a pod in the default namespace can access a service named my-service in the test namespace using the DNS name, my-service.test.svc.cluster.local.

Here’s an example YAML file to create a namespace and a service in Kubernetes:

This YAML file creates a namespace named “test” and a service named “my-service” within that namespace. The service selects the pods with the label app “my-app” and exposes port 80 to the cluster.

To verify that the DNS name for the service is working correctly, you can create a pod in the default namespace and run a DNS lookup:

This YAML file creates a pod named my-pod which runs an NGINX container. You can then log into the pod and run a DNS lookup for my-service.test.svc.cluster.local:

kubectl exec -it my-pod -- sh
# nslookup my-service.test.svc.cluster.local

The output of the “nslookup” command should show the IP address of the service:

This verifies that the DNS name for the service is working correctly within the test namespace.

How to Rename a Namespace

Renaming a namespace can be useful when you want to update the name to better reflect its purpose or to correct a naming mistake. However, renaming a namespace is not a straightforward process and requires some care to ensure that all the resources within the namespace are updated with the new name.

To rename a namespace in Kubernetes, you can follow these steps:

Update the namespace definition file to use the new name. This can be done by editing the YAML file directly or using the kubectl edit command.

Use “kubectl apply” to apply the updated namespace definition file.

Use “kubectl get” to list the resources in the old namespace and update them to use the new namespace name. This can be done by piping the output of “kubectl get” to kubectl apply with the –namespace flag set to the new namespace name. For example:

kubectl get all --namespace old-namespace | kubectl apply --namespace=new-namespace -f -

Delete the old namespace using the kubectl delete namespace old-namespace.

Here’s an example of YAML file to rename a namespace named old-namespace to new-namespace:

To apply the updated namespace definition file, you can use the following command:

kubectl apply -f new-namespace.yaml

To update the resources in the old namespace to use the new namespace name, you can use the following command:

kubectl get all --namespace old-namespace | kubectl apply --namespace=new-namespace -f

This command lists all the resources in the old-namespace namespace and pipes the output to “kubectl apply” with the –namespace flag set to new-namespace. The -f – flag tells the “kubectl apply” to read the YAML file from standard input.

Once all the resources are updated, you can delete the old namespace using the following command:

kubectl delete namespace old-namespace

This command deletes the old-namespace namespace and all the resources within it. Note that deleting a namespace is a non-reversible operation, so make sure to double-check before running this command.

How to Delete a Namespace

Deleting a namespace removes all the resources within it including any running pods and services. It’s important to be careful when deleting a namespace to avoid accidental data loss.

To delete a namespace in Kubernetes, you can use the “kubectl delete namespace” command followed by the name of the namespace that you want to delete. For example:

kubectl delete namespace my-namespace

This command deletes the my-namespace namespace and all the resources within it. Note that deleting a namespace is a non-reversible operation, so make sure to double-check before running this command.

If you have a lot of resources in the namespace and you want to delete them all at once, you can use the “kubectl delete” command with the –all flag. For example:

kubectl delete all --all --namespace my-namespace

This command deletes all the resources within the my-namespace namespace including the pods, services, deployments, and any other objects. Note that this command can be dangerous if you have resources in other namespaces with the same names as the ones in the namespace that you’re deleting.

Here’s an example of deleting a namespace and verifying that it has been removed:

The first command lists all the namespaces in the cluster including the “my-namespace” namespace. The second command deletes the “my-namespace” namespace and all the resources within it. The third command lists the namespaces again to verify that the “my-namespace” namespace has been removed.

Conclusion

Namespaces are a powerful feature of Kubernetes that allow you to organize and isolate the resources within your cluster. By using namespaces, you can provide better security, avoid naming conflicts, and simplify the management of your applications. In this article, we discussed what Kubernetes namespaces are, how they work, and the ways of using them effectively. We also covered how to create, view, rename, and delete the namespaces using the kubectl command-line tool.

Now that you have a good understanding of Kubernetes namespaces, you can start using them in your own Kubernetes deployments to better organize and manage your resources. To learn more about Kubernetes, check out the official Kubernetes documentation or consider taking a Kubernetes course or certification program. Happy Kubernetes clustering!

About the author

Nimesha Jinarajadasa

Being a Full-stack Senior Software Engineer for more than five years, I love technology, as technology has the power to solve our many problems within just a minute. I try to learn more and create more opportunities for this new world.