Complete guide to kubens commands for managing Kubernetes namespaces
kubens is a utility to switch between Kubernetes namespaces quickly. It provides a faster way to change the active namespace than using kubectl config set-context --current --namespace.
kubens new-feature --force# Active namespace is "new-feature".# The namespace doesn't exist yetkubectl get pods# Error from server (NotFound): namespaces "new-feature" not found# Create the namespacekubectl create namespace new-feature# namespace/new-feature created# Now kubectl commands workkubectl get pods# No resources found in new-feature namespace.
By default, kubens validates that the namespace exists before switching. Use --force only when you’re sure you want to set a namespace that doesn’t exist yet.
# Check what namespaces are availablekubens# Switch to production to check statuskubens production# Active namespace is "production".kubectl get pods# Lists pods in production# Quick check in stagingkubens staging# Active namespace is "staging".kubectl get pods# Lists pods in staging# Jump back to productionkubens -# Active namespace is "production".
# Start in your feature namespacekubens feature-auth-refactor# Active namespace is "feature-auth-refactor".# Deploy your changeskubectl apply -f deployment.yaml# Test against staging datakubens stagingkubectl port-forward svc/database 5432:5432# Back to your feature namespacekubens -# Run integration testskubectl logs -f deployment/api
kubens works with the current context. Combine with kubectx for multi-cluster workflows:
# Switch to dev clusterkubectx dev-cluster# Switched to context "dev-cluster".# Switch to your namespace in devkubens my-feature# Active namespace is "my-feature".# Switch to staging clusterkubectx staging-cluster# Switched to context "staging-cluster".# Switch to same namespace in stagingkubens my-feature# Active namespace is "my-feature".
kubens stores the previous namespace per context. Each context maintains its own history, so switching contexts doesn’t affect your namespace history.
By default, kubens validates that the namespace exists by querying the Kubernetes API:
# This will fail if namespace doesn't existkubens nonexistent# Error: no namespace exists with name "nonexistent"# Override validation with --forcekubens nonexistent --force# Active namespace is "nonexistent".
Namespace validation requires cluster connectivity. If you’re offline or the cluster is unreachable, use --force to set the namespace anyway.