Skip to content
Latchkey

kubectl "Error from server (NotFound): namespaces ... not found" in CI - Fix it

kubectl reached the API server, but the target namespace does not exist. Applying a namespaced resource into a missing namespace fails with NotFound; the namespace must be created before the resources that live in it.

What this error means

A kubectl apply -n prod or a manifest with namespace: prod fails with Error from server (NotFound): namespaces "prod" not found.

kubectl
Error from server (NotFound): error when creating "deploy.yaml": namespaces
"prod" not found

Common causes

The namespace was never created

A fresh cluster or a new environment has no prod namespace, and the deploy assumes it exists.

The namespace manifest applied after its resources

The Namespace object is in the set but ordered after the workloads that reference it.

How to fix it

Create the namespace before deploying into it

  1. Create the namespace idempotently at the start of the deploy.
  2. Apply the namespaced resources after it exists.
  3. Keep the Namespace manifest first in any combined apply.
Terminal
kubectl create namespace prod --dry-run=client -o yaml | kubectl apply -f -
kubectl apply -n prod -f k8s/

Order the Namespace manifest first

When applying a directory, name the namespace file so it sorts before the workloads, or apply it separately.

Terminal
kubectl apply -f namespace.yaml
kubectl apply -f deployment.yaml -f service.yaml

How to prevent it

  • Create target namespaces idempotently before each deploy.
  • Apply Namespace objects before the resources that use them.
  • Use a server-side dry run to catch missing namespaces early.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →