Objects and their lifecycle

Objects and their lifecycle

Anatomy of every object

apiVersion: apps/v1          # group/version
kind: Deployment             # type
metadata:                    # identity: name, namespace, labels, uid, ...
  name: web
spec:                        # desired state - written by you
  replicas: 3
status:                      # current state - written by controllers
  readyReplicas: 3
metadata fieldMeaning
uidunique for the object’s lifetime; a recreated object gets a new one
resourceVersionchanges on every write; used for optimistic locking
generationincrements when spec changes; compare with status.observedGeneration
ownerReferenceswho owns me - drives garbage collection
finalizerswork that must finish before deletion
deletionTimestampset when deletion was requested

Lifecycle

stateDiagram-v2 [*] --> Created: create / apply Created --> Reconciled: controllers act on spec Reconciled --> Reconciled: spec changes (generation++) Reconciled --> Terminating: delete (deletionTimestamp set) Terminating --> [*]: finalizers empty

Ownership and garbage collection

graph LR D[Deployment] -->|owns| RS[ReplicaSet] RS -->|owns| P1[Pod] RS -->|owns| P2[Pod]

Delete the owner and the garbage collector deletes the dependents.

kubectl delete deploy web                         # background (default)
kubectl delete deploy web --cascade=foreground    # owner waits for dependents
kubectl delete deploy web --cascade=orphan        # dependents stay, ownerless

Finalizers

A finalizer is a key in metadata.finalizers. While it is present, delete only sets deletionTimestamp and the object hangs in Terminating - until its controller does the clean-up and removes the key. Examples: kubernetes.io/pvc-protection, namespace finalizers, operator finalizers.

Warning

Removing a finalizer by hand makes the object disappear, but skips the clean-up it guarded. Find out why it is stuck first.

Graceful deletion of a Pod

delete -> Pod is marked Terminating and removed from Service endpoints -> SIGTERM -> up to terminationGracePeriodSeconds (30 s) -> SIGKILL.

References