Kubernetes

What are Kubernetes Namespaces? Usage Examples & Tutorial

Working with Kubernetes Namespaces

In this article, we will take a look at namespaces in Kubernetes, explain what they are and how to create them on the command line and in a configuration file, with some quick reference command examples using kubectl.

What we will cover:

  1. What is a namespace in Kubernetes?
  2. When to use a Kubernetes namespace?
  3. How to create a Kubernetes namespace
  4. Working with Kubernetes namespaces using kubectl
  5. Kubernetes namespaces best practices

What is a namespace in Kubernetes?

If a resource is namespaced, that means it cannot be created without a namespace.

Default namespaces in Kubernetes

By default, when you are creating a new Kubernetes cluster using a managed service, the following namespaces are created:

kubectl get namespaces                      

  • default – used for resources that don’t have a specific namespace specified when created
  • kube-node-lease – helps determine the availability of the nodes
  • kube-public – used for resources that need to be readable by all users
  • kube-system – contains the system processes such as DNS, dashboard, logging, and monitoring, among others

Kubernetes cluster vs. namespace

A Kubernetes cluster is spread among multiple compute nodes and contains multiple namespaces in which k8s resources are deployed. Not all resources in kubernetess are namespaced, meaning that some of them can be created globally.

Kubernetes namespace vs. pods

Pods are the most fundamental resources you can use inside your Kubernetes cluster for your workloads. They are namespaced, meaning they are always created inside a Kubernets namespace.

When to use a Kubernetes namespace?

Kubernetes Namespaces are critical for your Kubernetes workloads. They provide a logical separation between applications, environments, and teams.

When to use multiple namespaces?

There are multiple scenarios in which you will need to use multiple namespaces:

  1. Multi-Tenant Environments

Namespaces provide a way to isolate resources, ensuring that only team members with enough permissions can access them. By using namespaces in multi-tenant environments you can also take advantage of resource quotas and limits, making sure that no teams are overwhelming the cluster with their consumption.

  1. Environment Separation

Usually, when developing an application, it is best practice to have multiple environments to ensure that all changes are applied safely. With K8s namespaces, you can create one namespace per environment and deploy your application while ensuring that each environment can be managed independently. This is also helpful for credentials management as configmaps and secrets are namespaced resources, and you will most likely have different configurations based on the environment.

  1. Implementing Role-Based Access Control

Roles and Role Bindings are namespaced resources that allow you to define permissions within the scope of a namespace.

  1. Testing

Creating a separate namespace and deploying your application will help developers test their application while removing any risk associated with direct production changes.

How to create a Kubernetes namespace

You could create a namespace imperatively (using kubectl) or declaratively (using a YAML file).

Using YAML file

To create a namespace using the YAML file, let’s write a Kubernetes manifest that creates a that namespace:

# namespace.yaml
apiVersion: v1
kind: Namespace
metadata:
  name: jacks-blog

Now we can create it by running:

# Apply the namespace.yaml file
kubectl apply -f namespace.yml
kubernetes namespaces yaml file

Using kubectl

To create a Kubernetes namespace imperatively with kubectl, you can simply run this command:

kubectl create namespace my-namespace-imperative
namespace/my-namespace-imperative created

Tutorial: Working with Kubernetes namespaces using kubectl

Note that on the command line, if a namespace is not specified for a given kubectl command, then objects from the default namespace are shown.

1. View existing namespaces

To see objects within a specific namespace, the name of the namespace must be specified. Creating objects in the default namespace is considered a bad practice as it makes it harder to implement NetworkPolicies, use RBAC, and segregate objects. (Read more in our Kubernetes best practices article.)

# View existing namespaces
kubectl get namespaces

Here I have a namespace listed called ingress-nginx.

kubernetes namespaces ingress-nginx
  • default —The default namespace set by the system.
  • kube-system —This namespace is assigned to resources that are created by the Kubernetes system.
  • kube-public —This namespace is created by the system and is visible to all users, even users that aren’t authenticated.
  • kube-node-lease —This namespace holds lease objects associated with each node. These leases allow the kubelet to send heartbeats so that you can determine node availability.

2. List the pods contained in a namespace

# List the pods contained in a namespace
kubectl get pods --namespace ingress-nginx

# Note the short format for namespace can be used (-n)
kubectl get pods -n ingress-nginx
view the pods within the namespace

3. List pods in the default namespace

To view pods in the default namespace (no namespace specified):

# List pods in the default namespace
kubectl get pods
view pods in the default namespace

Note that my three pods in the ingress-nginx namespace are not displayed here.

4. Create a new namespace

To create a new namespace:

# Create a new namespace called jacks-blog
kubectl create namespace jacks-blog
create a new namespace
# Delete a namespace called jacks-blog
kubectl delete namespace jacks-blog
delete a namespace

Read more about the kubectl delete deployment command.

6. See details about a namespace

To see details about a namespace:

# Describe a namespace
kubectl describe namespace nginx-ingress
describe a namespace

7. Show resource usage of pods in a namespace

To see the resource usage (CPU / Memory) of pods in a particular namespace:

# Show resource usage of pods in ingress-nginx namespace
kubectl top pod --namespace=ingress-nginx
see the resource usage

See also How to Restart Kubernetes Pods With Kubectl.

8. Rename a namespace

While you cannot directly rename your namespace, what you can do is: 

  1. Save the configuration of it to a file.
kubectl get namespace my-namespace-declarative -o yaml > new_namespace.yaml
  1. Modify the name in the yaml file.
  2. Create the new namespace.
kubectl apply -f new_namespace.yaml                                        
namespace/my-namespace-declarative-modified created
  1. Repeat the above three steps for all the resources inside your namespace (you will need to modify the namespace parameter and not the name of the resource).
  2. Delete the old namespace.
kubectl delete namespace my-namespace-declarative
namespace "my-namespace-declarative" deleted

Kubernetes namespaces best practices

Namespaces are an important piece for your K8s cluster. They help with the overall separation, governance, and compliance of your Kubernetes resources.

Here are some of the best practices you should take advantage of:

1. Use meaningful names for your namespaces

Create your namespaces for specific use cases: environment separation, multi-tenant RBAC, testing, and others. By looking at a namespace name, you should be able to identify its purpose easily.

2. Implement resource quotas and limits

On the namespace level, you should ensure that resources have limits for CPU and memory, in order to avoid overloading the cluster. Also, using persistent volume claims for your storage helps in maintaining cluster performance.

3. Implementing role-based access control

Using the least privilege access method is a best practice for every IT tool or product, and K8s makes no difference. You need to create roles and role bindings to your namespaces and ensure that only authorized users have access to them. (To learn more, check out Guide to Kubernetes RBAC)

4. Implement network policies

Network policies are similar to security group / network access control list rules. With them, you can control pod communication and restrict connection between services that don’t need to interact.

5. Take advantage of monitoring and logging

Configure monitoring and logging as part of your cluster and set up alerts based on namespace-specific metrics. This can help in overseeing the cluster’s well-being and detect anomalies, while giving you the option to promptly address these issues.

6. Use multiple namespaces

Don’t create all your resources in a single namespace because, in that way, it will be impossible to implement all the best practices mentioned above. You should find a namespace split that works for your organization (application/environment/team), and put it to the test.

Key points

Namespaces are easy to work with in Kubernetes and can be manipulated using the kubectl command line tool, or declared in YAML configuration files. They allow objects to be grouped. Effective use of namespaces can make cluster management more streamlined.

Also, anything that can be run via kubectl can be run within a Spacelift stack. Spacelift helps you manage the complexities and compliance challenges of using Kubernetes. It brings with it a GitOps flow, so your Kubernetes Deployments are synced with your Kubernetes Stacks, and pull requests show you a preview of what they’re planning to change. It also has an extensive selection of policies, which lets you automate compliance checks and build complex multi-stack workflows.

Manage Kubernetes Faster and More Easily

Spacelift allows you to automate, audit, secure, and continuously deliver your infrastructure. It helps overcome common state management issues and adds several must-have features for infrastructure management.

Start free trial