Skip to content
Latchkey

kubectl create namespace: Usage, Options & Common CI Errors

Carve out an isolated namespace per branch or PR build.

kubectl create namespace makes a fresh namespace, the standard unit of isolation for an ephemeral CI environment. One namespace per PR or branch keeps test workloads and teardown cleanly separated.

What it does

kubectl create namespace NAME creates an empty namespace. Subsequent apply/create commands target it via -n NAME or by pinning it as the context default. Deleting the namespace cascades to everything inside it, which makes it the cleanest teardown primitive.

Common usage

Terminal
kubectl create namespace pr-${PR_NUMBER}
kubectl create namespace ci --dry-run=client -o yaml | kubectl apply -f -
kubectl apply -n pr-${PR_NUMBER} -f manifests/
kubectl delete namespace pr-${PR_NUMBER}          # cascading teardown

Common errors in CI

"AlreadyExists" on re-run is the trap - make it idempotent with kubectl create namespace ci --dry-run=client -o yaml | kubectl apply -f -, or guard with kubectl get namespace ci. Namespace names must be a DNS label (lowercase alphanumeric and -, ≤63 chars), so a branch name with slashes or uppercase fails "Invalid value" - sanitize it. Deleting a namespace can hang in Terminating if a contained resource has a stuck finalizer; that is the namespace-stuck-terminating problem, not a create issue, but it blocks recreating a same-named namespace until it clears.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →