0
0
KubernetesHow-ToBeginner · 3 min read

How to Create Namespace in Kubernetes: Simple Steps

To create a namespace in Kubernetes, use the kubectl create namespace <name> command or define it in a YAML file and apply it with kubectl apply -f <file>. Namespaces help organize and isolate resources within a cluster.
📐

Syntax

You can create a namespace in two main ways:

  • Command line: Use kubectl create namespace <name> where <name> is your namespace name.
  • YAML file: Define a namespace resource with apiVersion, kind, and metadata.name, then apply it.
bash
kubectl create namespace <name>
💻

Example

This example shows how to create a namespace named dev-environment using a YAML file and applying it with kubectl.

yaml
apiVersion: v1
kind: Namespace
metadata:
  name: dev-environment
Output
namespace/dev-environment created
⚠️

Common Pitfalls

Common mistakes when creating namespaces include:

  • Trying to create a namespace that already exists, which causes an error.
  • Forgetting to specify the namespace when creating resources, so they go to the default namespace.
  • Incorrect YAML indentation or missing required fields like metadata.name.
bash
kubectl create namespace dev-environment
# Wrong: creating again without deleting
kubectl create namespace dev-environment

# Right: check if exists before creating
kubectl get namespace dev-environment || kubectl create namespace dev-environment
Output
Error from server (AlreadyExists): namespaces "dev-environment" already exists namespace/dev-environment
📊

Quick Reference

CommandDescription
kubectl create namespace Create a namespace directly via command line
kubectl apply -f Create namespace from a YAML file
kubectl get namespacesList all namespaces in the cluster
kubectl delete namespace Delete a namespace

Key Takeaways

Use kubectl create namespace <name> or YAML files to create namespaces.
Namespaces help organize Kubernetes resources and isolate environments.
Always check if a namespace exists before creating to avoid errors.
Specify the namespace when creating resources to avoid placing them in default.
YAML files must include apiVersion, kind, and metadata.name.