0
0
Kubernetesdevops~5 mins

Creating custom namespaces in Kubernetes - Step-by-Step CLI Walkthrough

Choose your learning style9 modes available
Introduction
When you run many applications in Kubernetes, they can get mixed up and hard to manage. Creating custom namespaces helps keep your apps organized by grouping related resources together.
When you want to separate development and production environments in the same cluster.
When multiple teams share the same Kubernetes cluster and need isolated spaces.
When you want to apply different access controls to different groups of resources.
When you want to limit resource usage for a specific group of applications.
When you want to organize resources by project or application type.
Config File - namespace.yaml
namespace.yaml
apiVersion: v1
kind: Namespace
metadata:
  name: example-namespace

This file defines a new namespace named example-namespace. The apiVersion and kind tell Kubernetes what type of object this is. The metadata.name sets the namespace's name.

Commands
This command creates the custom namespace defined in the namespace.yaml file. It tells Kubernetes to add this new isolated space.
Terminal
kubectl apply -f namespace.yaml
Expected OutputExpected
namespace/example-namespace created
This command lists all namespaces in the cluster so you can verify your new namespace was created.
Terminal
kubectl get namespaces
Expected OutputExpected
NAME STATUS AGE default Active 10d kube-system Active 10d example-namespace Active 1m
This command sets your current kubectl context to use the new namespace by default, so you don't have to specify it in every command.
Terminal
kubectl config set-context --current --namespace=example-namespace
Expected OutputExpected
Context "your-cluster-context" modified.
This command lists pods in the current namespace, which is now example-namespace. It helps confirm you are working inside the right namespace.
Terminal
kubectl get pods
Expected OutputExpected
No resources found in example-namespace namespace.
Key Concept

If you remember nothing else from this pattern, remember: namespaces create isolated spaces in Kubernetes to organize and separate resources.

Common Mistakes
Not creating a namespace before trying to deploy resources into it.
Kubernetes will fail to find the namespace and the deployment will not work.
Always create the namespace first using a YAML file or kubectl before deploying resources there.
Forgetting to switch the kubectl context to the new namespace.
kubectl commands will run in the default namespace, causing confusion or resource deployment in the wrong place.
Use 'kubectl config set-context --current --namespace=your-namespace' to switch namespaces.
Summary
Create a namespace YAML file to define a new isolated space.
Apply the YAML file with kubectl to create the namespace.
List namespaces to verify creation.
Set your kubectl context to the new namespace for easier management.