Finalizers

    When you tell Kubernetes to delete an object that has finalizers specified for it, the Kubernetes API marks the object for deletion, putting it into a read-only state. The target object remains in a terminating state while the control plane, or other components, take the actions defined by the finalizers. After these actions are complete, the controller removes the relevant finalizers from the target object. When the field is empty, Kubernetes considers the deletion complete.

    You can use finalizers to control garbage collection of resources. For example, you can define a finalizer to clean up related resources or infrastructure before the controller deletes the target resource.

    You can use finalizers to control of resources by alerting controllers to perform specific cleanup tasks before deleting the target resource.

    When you create a resource using a manifest file, you can specify finalizers in the metadata.finalizers field. When you attempt to delete the resource, the controller that manages it notices the values in the finalizers field and does the following:

    • Marks the object as read-only until its field is empty.

    The controller then attempts to satisfy the requirements of the finalizers specified for that resource. Each time a finalizer condition is satisfied, the controller removes that key from the resource’s finalizers field. When the field is empty, garbage collection continues. You can also use finalizers to prevent deletion of unmanaged resources.

    A common example of a finalizer is kubernetes.io/pv-protection, which prevents accidental deletion of PersistentVolume objects. When a object is in use by a Pod, Kubernetes adds the pv-protection finalizer. If you try to delete the PersistentVolume, it enters a Terminating status, but the controller can’t delete it because the finalizer exists. When the Pod stops using the , Kubernetes clears the pv-protection finalizer, and the controller deletes the volume.

    The Job controller also adds owner references to those Pods, pointing at the Job that created the Pods. If you delete the Job while these Pods are running, Kubernetes uses the owner references (not labels) to determine which Pods in the cluster need cleanup.

    Kubernetes also processes finalizers when it identifies owner references on a resource targeted for deletion.

    In some situations, finalizers can block the deletion of dependent objects, which can cause the targeted owner object to remain in a read-only state for longer than expected without being fully deleted. In these situations, you should check finalizers and owner references on the target owner and dependent objects to troubleshoot the cause.