English

Share with friends

Note

Namespace in Kubernetes provides a way to categorize applications, streamline resource management, and fosters team collaboration. In this Kubernetes Namespace tutorial, we'll delve into the concept of namespaces, unravel their capabilities, and guide you through creating your own.

Get ready to unlock the magic of namespaces in Kubernetes!

Kubernetes Namespace Tutorial: Everything You Need to Know About Namespace in K8s cover image

In container orchestration, namespaces emerge as a vital construct, offering a robust solution for managing applications and resources.

Picture a virtual metropolis within your Kubernetes cluster, where applications reside in their designated spaces, thriving in harmony.

In this blog post, we'll embark on an exciting journey to demystify the concept of namespaces in Kubernetes. We will unravel their true essence and equip you with the knowledge to create them effortlessly.

So let's get started!

What is Namespace in Kubernetes?

A namespace is crucial for organizing and managing resources within a cluster in Kubernetes. It provides a logical boundary allowing you to partition your cluster into distinct environments, each with its own applications and resources.

At its core, a namespace is a virtual cluster that operates within the Kubernetes cluster itself. It ensures that resources like pods, services, and deployments are organized and isolated, preventing conflicts and enabling efficient resource management.

By creating namespaces, you can effectively separate different applications, teams, or projects within the same cluster, avoiding naming collisions and promoting a more streamlined and scalable environment.

Why Use Namespace in Kubernetes?

Seamless Coexistence and Collaboration

Imagine a bustling metropolis where each team or project can thrive in its virtual cluster without fear of impacting others. Namespaces provide a solution by creating logical boundaries within your Kubernetes cluster.

With namespaces, you can ensure that different teams or projects operate in their designated spaces, enjoying the benefits of isolation while fostering seamless coexistence and collaboration.

Enhanced Role-Based Access Controls

Access control is a critical aspect of any robust system, and Kubernetes namespaces offer an excellent tool to enhance Role-Based Access Controls (RBAC).

By limiting users and processes to specific namespaces, you can enforce fine-grained permissions, ensuring that each team or user has access only to the resources and applications within their designated namespace.

This strengthens security, reduces the risk of unauthorized access, and promotes a more controlled and manageable environment.

Efficient Resource Allocation

Resource allocation can become a challenge in a Kubernetes cluster, especially when multiple teams or users coexist.

Namespaces come to the rescue by enabling the division of cluster resources among different teams or projects using resource quotas.

By assigning resource limits and quotas to namespaces, you can ensure fair distribution of computing resources, prevent resource contention, and maintain optimal cluster performance.

Streamlined Application Lifecycle

With namespaces, you can easily separate and manage the entire lifecycle of containerized applications within a single cluster.

You can organize your applications and streamline the workflow by creating distinct namespaces for development, testing, and deployment stages.

This enables teams to focus on specific stages without interfering with others, resulting in a more efficient and seamless application lifecycle management process.

Also Read: Kubernetes Secrets Tutorial

When to Use Namespace in Kubernetes?

Isolation: Embracing Collaboration, Minimizing Interference

One of the primary reasons to leverage namespaces is the ability to isolate projects and microservices from one another.

This proves especially useful for large or growing teams, where the coexistence of multiple projects can become complex.

With namespaces, teams can work in virtual spaces without worrying about conflicts or unintended consequences.

Each namespace acts as a sandbox, allowing teams to reuse resource names and take actions without impacting other namespaces.

This seamless isolation fosters collaboration while minimizing interference, enabling teams to work efficiently and independently.

Organization: Safeguarding Production, Streamlining Application Life Cycles

Namespaces offer a powerful organizational tool for organizations utilizing a single Kubernetes cluster throughout the application lifecycle.

By sandboxing development and testing environments within their namespaces, organizations can ensure that production code remains untouched by changes made in other namespaces.

This level of organization prevents accidental disruptions and provides a structured framework for managing application lifecycles.

With namespaces, each stage of development, testing, and production can operate independently, enabling seamless transitions while maintaining the integrity of the production environment.

Permissions: Fine-Grained Control, Strengthened Security

Namespaces are crucial in enforcing permissions and access control through Kubernetes Role-Based Access Control (RBAC).

Teams can define roles encompassing permissions or abilities, ensuring that only authorized users have access to resources within a specific namespace.

This granular control strengthens security, mitigates unauthorized access or data breach risks, and allows for seamless collaboration within each namespace.

Resource Control: Fair Allocation, Preventing Resource Hogging

Efficient resource management is critical for optimized cluster performance. Namespaces facilitate policy-driven resource control by enabling the definition of resource quotas for CPU or memory utilization.

This ensures that each project or namespace has the necessary resources to run without being compromised by resource-intensive workloads in other namespaces.

With resource quotas in place, organizations can prevent resource hogging, maintain fair allocation, and promote an environment where every project receives the necessary resources for smooth operation.

Kubernetes Namespace vs Cluster

Kubernetes namespaces and clusters are fundamental components of the Kubernetes ecosystem, each serving a distinct purpose.

A Kubernetes cluster is the foundation of scalability, consisting of nodes that run applications and provide the necessary resources for container orchestration.

It ensures fault tolerance, high availability, and efficient resource utilization.

On the other hand, a Kubernetes namespace is a virtual environment within a cluster, allowing for the isolation and organization of resources, applications, and services.

Namespaces enable teams or projects to operate independently, preventing naming conflicts and providing access control through RBAC.

While clusters provide the infrastructure, namespaces create logical boundaries and facilitate collaboration.

Multiple namespaces can coexist within a single cluster, enabling teams to work autonomously and ensuring resource allocation fairness.

Also Read: Docker Commands Cheatsheet

Kubernetes Namespace vs Pods

Kubernetes namespaces and pods are distinct entities that serve different purposes within the Kubernetes ecosystem.

A Kubernetes namespace provides logical isolation and organization, acting as a virtual cluster within the larger infrastructure.

It enables teams or projects to work independently, preventing naming conflicts and allowing for resource allocation and access control at the namespace level.

On the other hand, a Kubernetes pod is the fundamental unit of deployment, representing one or more tightly coupled containers running on the same node.

Pods sum up containers and facilitate efficient communication and resource sharing within a cluster.

While namespaces focus on creating boundaries and managing resources at a higher level, pods sum up and manage containers more granularly.

Kubernetes Namespace vs Node

Kubernetes namespaces and nodes are essential components of the Kubernetes ecosystem, each playing a crucial role in the management and execution of containerized applications.

A Kubernetes namespace acts as a virtual cluster, providing logical isolation and organization within a Kubernetes cluster.

It enables teams or projects to operate independently, ensuring resource partitioning and preventing naming conflicts.

Namespaces allow for efficient resource management, access control, and collaboration within the cluster.

On the other hand, Kubernetes nodes represent the underlying compute resources, either physical or virtual machines, that make up the cluster.

Nodes host and execute the containers sum upd within pods. They provide the necessary computing power, storage, and networking capabilities for running applications.

Nodes manage and orchestrate containers, ensuring their availability and scalability.

Also Read: Only Kubect Cheatsheet You'll Ever Need

Default Kubernetes Namespaces

In Kubernetes, there are four default namespaces that are created when setting up a cluster. These namespaces are automatically provisioned and serve specific purposes:

default: This is the default namespace for objects that are not explicitly assigned to a specific namespace.

If you create resources without specifying a namespace, they will be created in the default namespace by default. It's recommended to create and use custom namespaces instead of placing resources directly in the default namespace.

kube-system: The kube-system namespace is reserved for Kubernetes system components and infrastructure-related resources.

It houses critical components such as the cluster's control plane, cluster DNS (CoreDNS), and resource controllers like the kube-proxy and kube-dns.

kube-public: The kube-publicnamespace is accessible to all users (authenticated and unauthenticated) and can be used for resources that need to be publicly available across the entire cluster.

It is typically used for cluster information and resources that need to be shared with all namespaces, such as the cluster's public configuration.

kube-node-lease: The kube-node-lease namespace is responsible for housing lease objects created by each node in the cluster. These lease objects indicate that a node is operational and alive.

These default namespaces are created during the initial setup of a Kubernetes cluster and serve specific purposes related to the functioning and management of the cluster.

It's important to be mindful of the resources placed in each namespace and consider creating custom namespaces for organizing and isolating different application workloads and environments.

Note

For a production cluster, consider not using the default namespace. Instead, make other namespaces and use those.

How do Pods Communicate across Different Namespaces in Kubernetes?

A Pod can connect with another Pod by directly addressing its IP address, although Services is the preferred method.

A Service is a collection of Pods that can be accessed by a single, fixed DNS name or IP address.

In actuality, most Kubernetes applications connect with one another using Services. Pods can communicate with each other using their IP addresses by default, independent of the namespace.

You can see the IP address of each pod with:

kubectl get pods -o wide --all-namespaces

However, the most common approach for a cluster to communicate is through Service resources.

A Service has an IP address as well as a DNS name. A Service is supported by a collection of pods. The Service routes requests to one of the backing pods.

A Service's fully qualified DNS name is:

<service-name>.<service-namespace>.svc.cluster.local

This can be resolved to the Service's IP address from any location in the cluster (regardless of namespace).

Also, Kubernetes Network Policies allow you to define fine-grained rules for network traffic within the cluster.

By creating Network Policies, you can specify which namespaces are allowed to communicate with each other.

By configuring appropriate network policies, you can enable communication between Pods in different namespaces while maintaining security and control over the traffic.

It's important to note that enabling cross-namespace communication should be done with caution, as it may introduce security and management complexities.

Consider the security requirements and implications of allowing communication between namespaces in your specific use case.

Also Read: Top 24+ K8s Best Practices

Kubernetes Namespace Best Practices

Here are some Kubernetes namespace best practices along with example commands to demonstrate their implementation.

Apply Resource Quotas and Limits

To set resource quotas and limits for a namespace, you can use the kubectl apply command with a YAML file defining the quota and limit specifications.

Here's an example:

# quota.yaml
apiVersion: v1
kind: ResourceQuota
metadata:
  name: my-quota
spec:
  hard:
    pods: "10"
    requests.cpu: "4"
    requests.memory: 4Gi
    limits.cpu: "8"
    limits.memory: 8Gi

Apply the quota to the namespace using:

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

Define RBAC for Namespace Access Control

To set up RBAC rules for a namespace, create role and role-binding objects. Here's an example:

# role.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: my-role
rules:
  - apiGroups: [""]
    resources: ["pods"]
    verbs: ["get", "list", "create", "delete"]
---
# role-binding.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: my-role-binding
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: my-role
subjects:
  - kind: User
    name: [email protected]

Apply the role and role binding to the namespace using:

kubectl apply -f role.yaml --namespace=my-namespace
kubectl apply -f role-binding.yaml --namespace=my-namespace

Add Annotations and Labels to Namespaces

To add annotations and labels to a namespace, use the kubectl annotate and kubectl label commands.

Here's an example:

kubectl annotate namespace my-namespace description="My example namespace"
kubectl label namespace my-namespace environment=production

Namespace Naming Conventions

Establish a consistent naming convention for your namespaces. This can help distinguish between different types of namespaces, making it easier to identify their purpose and associated resources.

For example, you could prefix namespaces with the project or team name followed by an identifier.

Namespace Deletion Policies

Establish policies for namespace lifecycle management. Define guidelines for when and how namespaces should be deleted, especially for temporary (aka ephemeral environments) or test environments.

Regularly review and clean up unused namespaces to free up resources and avoid clutter within the cluster.

Monitoring and Observability

This includes tracking resource utilization, monitoring events and logs, and setting up alerts for namespace-specific metrics.

It enables you to proactively identify and address issues within namespaces, ensuring optimal performance and stability.

Also Read: Prometheus Operator Tutorial

Documentation and Naming Conventions for Objects

Encourage teams to follow consistent naming conventions for objects (pods, services, deployments, etc.) within namespaces.

By following these Kubernetes namespace best practices, you can enhance the management, organization, and security of your Kubernetes cluster, ensuring smooth operations and efficient resource utilization.

How to Create a Namespace in Kubernetes?

To create a namespace in Kubernetes, you can use the kubectl create namespace command. Here's the syntax:

kubectl create namespace <namespace-name>

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

For example, to create a namespace called "my-namespace", you would run:

kubectl create namespace my-namespace

Once executed, Kubernetes will create the specified namespace within your cluster.

After creating the namespace, you can start deploying and managing your resources within that namespace using the kubectl command.

For example, you can create pods, services, deployments, and other Kubernetes objects specific to the newly created namespace.

How to View Namespace in Kubernetes?

To view the namespaces in your Kubernetes cluster, you can use the kubectl get namespaces command. Here's how you can do it:

kubectl get namespaces

Executing this command will provide you with a list of all the namespaces present in your cluster, along with some additional information such as their status, age, and labels.

Sample output:

NAME                 STATUS   AGE
default              Active    3d
kube-node-lease      Active    3d
kube-public          Active    3d
kube-system          Active    3d

In this example, you can see the default namespaces provided by Kubernetes: default, kube-node-lease, kube-public, and kube-system.

These namespaces are typically created by default when setting up a Kubernetes cluster.

The STATUS column indicates whether the namespace is active or not, and the AGE column displays the duration since the namespace was created.

Also Read: Kubectl Config Set Context Tutorial

How to Switch Namespace in Kubernetes?

To switch the active namespace in Kubernetes, you can use the kubectl config set-context command.

Follow these steps:

  1. List the available namespaces and identify the one you want to switch to using the kubectl get namespaces command:
kubectl get namespaces

Sample output:

NAME                      STATUS   AGE
default           	      Active    3d
kube-node-lease           Active    3d
kube-public               Active    3d
kube-system               Active    3d
my-namespace              Active    2d
  1. Set the desired namespace as the active namespace using the kubectl config set-context command:
kubectl config set-context --current --namespace=<namespace-name>

Replace <namespace-name> with the name of the namespace you want to switch to.

For example, to switch to the "my-namespace" namespace, you would run:

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

This command sets the specified namespace as the active namespace in your current context.

  1. Verify that the namespace switch was successful by running any kubectl command. The command output will now display resources from the switched namespace.

For example, to list the pods in the current namespace, you can use:

kubectl get pods

The output will show the pods within the switched namespace.

By following these steps, you can switch the active namespace in Kubernetes and work with resources within the desired namespace using the kubectl commands.

Also Read: Differences between Kubernetes Cluster Autoscaler and Karpenter

How to Specify Namespace in YAML?

To specify the namespace for Kubernetes resources in a YAML file, you can use the metadata.namespace field.

Here's an example of how to do it:

apiVersion: v1
kind: Pod
metadata:
  name: my-pod
  namespace: my-namespace
spec:
  containers:
    - name: my-container
      image: nginx:latest

In this example, we have a Pod definition YAML file. The metadata.namespace field is set to "my-namespace", which specifies that the Pod should be created in the "my-namespace" namespace.

You can apply this YAML file using the kubectl apply command:

kubectl apply -f pod.yaml

By setting the metadata.namespace field in the YAML file, you ensure that the resource will be created within the specified namespace when applying the YAML manifest.

Remember that if you don't explicitly specify the namespace in the YAML file, the resource will be created in the default namespace of your Kubernetes cluster.

Also Read: Is Using Kubernetes for Your Startups a Good Idea?

Namespaces in Kubernetes facilitate sharing a cluster by providing logical separation and resource isolation.

Let's explore how namespaces enable sharing a cluster using commands and examples:

Create Namespaces

To create a namespace, you can use the kubectl create namespace command. For example, to create a namespace named "team-a":

kubectl create namespace team-a

This command creates a new namespace named "team-a" within the cluster.

Deploy Resources to Namespaces

Once the namespaces are created, teams or applications can deploy their resources into their respective namespaces.

For example, to deploy a sample application into the "team-a" namespace, you can use a YAML manifest file:

apiVersion: v1
kind: Pod
metadata:
  name: my-app
  namespace: team-a
spec:
  containers:
    - name: my-app-container
      image: my-app-image:latest

Save the above content in a file named my-app.yaml, and then run the following command to deploy the resource:

kubectl apply -f my-app.yaml

This will create a Pod named "my-app" within the "team-a" namespace.

Access Resources in Namespaces

To access resources in specific namespaces, you need to specify the namespace in the command.

For example, to list all Pods in the "team-a" namespace:

kubectl get pods --namespace=team-a

This command will list all the Pods running in the "team-a" namespace.

Namespace-scoped Services

By default, Services created within a namespace are accessible only within that namespace.

For example, to create a Service that targets Pods within the "team-a" namespace:

apiVersion: v1
kind: Service
metadata:
  name: my-app-service
  namespace: team-a
spec:
  selector:
    app: my-app
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080

Save the above content in a file named my-app-service.yaml, and then run the following command to create the Service:

kubectl apply -f my-app-service.yaml

This will create a Service named "my-app-service" within the "team-a" namespace.

To access this Service from within the same namespace, you can use its DNS name (my-app-service.team-a) or the Service's ClusterIP.

Role-based Access Control (RBAC)

Kubernetes provides RBAC mechanisms to control access to resources. You can define roles and role bindings to grant permissions at the namespace level.

For example, to grant "edit" access to a user in the "team-a" namespace:

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: team-a-edit
  namespace: team-a
subjects:
  - kind: User
    name: [email protected]
    apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: Role
  name: edit
  apiGroup: rbac.authorization.k8s.io

Save the above content in a file named team-a-edit.yaml, and then run the following command to create the role binding:

kubectl apply -f team-a-edit.yaml

This grants the user [email protected] "edit" access within the "team-a" namespace

By using commands like kubectl create namespace, kubectl apply, and specifying the namespace flag (--namespace) with various commands, you can create namespaces, deploy resources into namespaces, access resources within namespaces, and configure RBAC for specific namespaces.

This allows teams or applications to share a Kubernetes cluster while maintaining separation and control over their resources and access.

Also Read: Best Kubernetes Cost Optimization Tools

How to Create K8s Deployment in Specific Namespace?

To create a Kubernetes Deployment in a specific namespace, you need to specify the namespace in the YAML manifest or with the kubectl command. Here's how you can create a Deployment in a specific namespace:

Specifying Namespace in YAML Manifest

Create a YAML manifest file, such as my-deployment.yaml, and specify the namespace using the metadata.namespace field. Here's an example:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-deployment
  namespace: my-namespace

Save the manifest file and run the following command to create the Deployment:

kubectl apply -f my-deployment.yaml

This will create a Deployment named "my-deployment" in the "my-namespace" namespace.

Specifying Namespace with kubectl Command

If you prefer to specify the namespace with the kubectl command, you can use the --namespace flag.

Here's an example:

kubectl create deployment my-deployment --image=my-app-image:latest --namespace=my-namespace

This command creates a Deployment named "my-deployment" with the specified image in the "my-namespace" namespace.

After creating the Deployment, you can use commands like kubectl get deployments --namespace=my-namespace to list deployments in the specific namespace or kubectl get pods --namespace=my-namespace to list pods in the namespace.

Note

Remember to replace "my-namespace" with the actual name of the namespace where you want to create the Deployment.

How to Delete a Namespace in Kubernetes?

To delete a namespace in Kubernetes, you can use the kubectl delete namespace command. Follow these steps:

  1. List the available namespaces to identify the one you want to delete using the kubectl get namespaces command:
kubectl get namespaces
  1. Delete the desired namespace using the kubectl delete namespace command:
kubectl delete namespace <namespace-name>

Replace <namespace-name> with the name of the namespace you want to delete.

For example, to delete the "my-namespace" namespace, you would run:

kubectl delete namespace my-namespace

This command deletes the specified namespace, along with all the resources (pods, deployments, services, etc.) within it.

  1. Verify that the namespace has been deleted by listing the namespaces again:
kubectl get namespaces

If the namespace no longer appears in the list, it has been successfully deleted.

Deleting a namespace will remove all resources associated with it, so exercise caution when executing this command.

It's recommended to review the namespace and its contents before deletion to avoid the accidental removal of important resources.

By following these steps, you can delete a namespace in Kubernetes using the kubectl delete namespace command.

Also Read: What are Init Containers in Kubernetes?

How to Rename Namespace in Kubernetes?

Renaming a namespace in Kubernetes is not supported directly through a built-in command or API operation.

However, you can achieve a similar effect by creating a new namespace with the desired name and migrating the resources from the old namespace to the new one.

Here's the general process to rename a namespace:

Step 1: Create a new namespace.

kubectl create namespace <new-namespace-name>

Step 2: Move resources from the old namespace to the new namespace.

You can use the kubectl command along with label selectors to select and move resources.

For example, to move all the pods from the old namespace to the new one:

kubectl get pods --namespace=<old-namespace-name> -o name | xargs -I {} kubectl patch {} --namespace=<new-namespace-name> -p '{"metadata":{"namespace":"<new-namespace-name>"} }'

Replace <old-namespace-name> and <new-namespace-name> with the appropriate names.

This command retrieves all the pods from the old namespace and patches their metadata to update the namespace field to the new namespace.

Repeat this step for other resource types like services, deployments, or config maps, using the respective kubectl commands and label selectors.

Step 3: Verify that the resources have been moved successfully to the new namespace.

kubectl get pods --namespace=<new-namespace-name>

Ensure that all the desired resources are present in the new namespace.

Step 4: Delete the old namespace.

kubectl delete namespace <old-namespace-name>

This step removes the old namespace along with any remaining resources it may contain.

By following these steps, you can effectively "rename" a namespace in Kubernetes by creating a new namespace, migrating the resources, and deleting the old namespace.

However, it's important to note that this approach does not preserve certain attributes like creation timestamps or owner references.

Therefore, it's recommended to thoroughly test and plan the renaming process before executing it in a production environment.

Kubernetes Call Service in Another Namespace

Let's assume you have two namespaces: 'namespace1' and 'namespace2', and you want to call a service named 'my-service' in 'namespace2' from 'namespace1'.

Firstly, let's deploy the service in 'namespace2'# my-service.yaml

apiVersion: v1
kind: Service
metadata:
  name: my-service
  namespace: namespace2
spec:
  selector:
    app: my-app
  ports:
    - name: http
      port: 80
      targetPort: 8080

Now, let's look at how to deploy a pod or deployment in 'namespace1' and call the 'my-service' in 'namespace2'.

# my-pod.yaml
apiVersion: v1
kind: Pod
metadata:
  name: my-pod
  namespace: namespace1
spec:
  containers:
    - name: my-container
      image: my-image
      command: ["curl"]
           args: ["my-service.namespace2.svc.cluster.local"]

In the 'args' section of the pod's definition, we use the FQDN of the 'my-service' in the format 'my-service.namespace2.svc.cluster.local'. This FQDN allows the pod in 'namespace1' to resolve and call the service in 'namespace2'.

You can adjust the FQDN based on your specific cluster configuration. The format is <service-name>.<namespace>.svc.cluster.local.

By making an HTTP request to 'my-service.namespace2.svc.cluster.local', you can communicate with the 'my-service' from the 'namespace1' pod or deployment.

Also Read: Differences between Kubernetes and Docker Swarm

FAQs

What is the purpose of a namespace?

A Kubernetes namespace provides isolation and organization within a cluster, allowing teams or projects to work independently and efficiently manage resources.

What is the maximum number of namespaces in Kubernetes?

There is no set maximum limit on the number of namespaces in Kubernetes.

Share with friends

Priyansh Khodiyar's profile

Written by Priyansh Khodiyar

Priyansh is the founder of UnYAML and a software engineer with a passion for writing. He has good experience with writing and working around DevOps tools and technologies, APMs, Kubernetes APIs, etc and loves to share his knowledge with others.

Further Reading

Life is better with cookies 🍪

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt out if you wish. Cookie Policy