kubectl apply "field is immutable" on an existing resource in CI - Fix it
Some fields are fixed for a resource's lifetime: a Deployment's spec.selector, a Service's clusterIP, a Job's spec.template. Changing one and re-applying is rejected with "field is immutable". The resource must be recreated, not patched.
What this error means
A kubectl apply over an existing object fails with The Deployment "api" is invalid: spec.selector: Invalid value: ...: field is immutable after you edited a selector or another fixed field.
The Deployment "api" is invalid: spec.selector: Invalid value:
v1.LabelSelector{...}: field is immutableCommon causes
An immutable field changed between deploys
A selector, clusterIP, or other fixed field differs from the live object, and Kubernetes does not allow updating it in place.
A label/selector refactor applied to a live object
Renaming match labels rewrites the selector, which a running Deployment treats as immutable.
How to fix it
Recreate the resource instead of patching it
- Confirm which field the message says is immutable.
- Delete the existing resource (accepting the brief gap) and apply the new spec.
- For zero-downtime, roll out under a new name and shift traffic.
kubectl delete deployment api
kubectl apply -f deployment.yamlKeep immutable fields stable across deploys
Treat the selector as a fixed contract; change pod template labels without altering the selector.
spec:
selector:
matchLabels:
app: api # do not change once deployedHow to prevent it
- Never change a Deployment selector or Service clusterIP on a live object.
- Recreate (or blue/green) when an immutable field must change.
- Review manifest diffs for immutable-field edits before applying.