Persistent VolumesThis document describes persistent volumes in Kubernetes. Familiarity with volumes, StorageClasses and VolumeAttributesClasses is suggested.IntroductionManaging storage is a distinct problem from managing compute instances. The PersistentVolume subsystem provides an API for users and administrators that abstracts details of how storage is provided from how it is consumed. To do this, we introduce two new API resources: PersistentVolume and PersistentVolumeClaim.A PersistentVolume (PV) is a piece of storage in the cluster that has been provisioned by an administrator or dynamically provisioned using Storage Classes. It is a resource in the cluster just like a node is a cluster resource. PVs are volume plugins like Volumes, but have a lifecycle independent of any individual Pod that uses the PV. This API object captures the details of the implementation of the storage, be that NFS, iSCSI, or a cloud-provider-specific storage system.A PersistentVolumeClaim (PVC) is a request for storage by a user. It is similar to a Pod. Pods consume node resources and PVCs consume PV resources. Pods can request specific levels of resources (CPU and Memory). Claims can request specific size and access modes (e.g., they can be mounted ReadWriteOnce, ReadOnlyMany, ReadWriteMany, or ReadWriteOncePod, see AccessModes).While PersistentVolumeClaims allow a user to consume abstract storage resources, it is common that users need PersistentVolumes with varying properties, such as performance, for different problems. Cluster administrators need to be able to offer a variety of PersistentVolumes that differ in more ways than size and access modes, without exposing users to the details of how those volumes are implemented. For these needs, there is the StorageClass resource.See the detailed walkthrough with working examples.Lifecycle of a volume and claimPVs are resources in the cluster. PVCs are requests for those resources and also act as claim checks to the resource. The interaction between PVs and PVCs follows this lifecycle:ProvisioningThere are two ways PVs may be provisioned: statically or dynamically.StaticA cluster administrator creates a number of PVs. They carry the details of the real storage, which is available for use by cluster users. They exist in the Kubernetes API and are available for consumption.DynamicWhen none of the static PVs the administrator created match a user's PersistentVolumeClaim, the cluster may try to dynamically provision a volume specially for the PVC. This provisioning is based on StorageClasses: the PVC must request a storage class and the administrator must have created and configured that class for dynamic provisioning to occur. Claims that request the class "" effectively disable dynamic provisioning for themselves.To enable dynamic storage provisioning based on storage class, the cluster administrator needs to enable the DefaultStorageClass admission controller on the API server. This can be done, for example, by ensuring that DefaultStorageClass is among the comma-delimited, ordered list of values for the --enable-admission-plugins flag of the API server component. For more information on API server command-line flags, check kube-apiserver documentation.BindingA user creates, or in the case of dynamic provisioning, has already created, a PersistentVolumeClaim with a specific amount of storage requested and with certain access modes. A control loop in the control plane watches for new PVCs, finds a matching PV (if possible), and binds them together. If a PV was dynamically provisioned for a new PVC, the loop will always bind that PV to the PVC. Otherwise, the user will always get at least what they asked for, but the volume may be in excess of what was requested. Once bound, PersistentVolumeClaim binds are exclusive, regardless of how they were bound. A PVC to PV binding is a one-to-one mapping, using a ClaimRef which is a bi-directional binding between the PersistentVolume and the PersistentVolumeClaim.Claims will remain unbound indefinitely if a matching volume does not exist. Claims will be bound as matching volumes become available. For example, a cluster provisioned with many 50Gi PVs would not match a PVC requesting 100Gi. The PVC can be bound when a 100Gi PV is added to the cluster.UsingPods use claims as volumes. The cluster inspects the claim to find the bound volume and mounts that volume for a Pod. For volumes that support multiple access modes, the user specifies which mode is desired when using their claim as a volume in a Pod.Once a user has a claim and that claim is bound, the bound PV belongs to the user for as long as they need it. Users schedule Pods and access their claimed PVs by including a persistentVolumeClaim section in a Pod's volumes block. See Claims As Volumes for more details on this.Storage Object in Use ProtectionThe purpose of the Storage Object in Use Protection feature is to ensure that PersistentVolumeClaims (PVCs) in active use by a Pod and PersistentVolume (PVs) that are bound to PVCs are not removed from the system, as this may result in data loss.Note:PVC is in active use by a Pod when a Pod object exists that is using the PVC.If a user deletes a PVC in active use by a Pod, the PVC is not removed immediately. PVC removal is postponed until the PVC is no longer actively used by any Pods. Also, if an admin deletes a PV that is bound to a PVC, the PV is not removed immediately. PV removal is postponed until the PV is no longer bound to a PVC.You can see that a PVC is protected when the PVC's status is Terminating and the Finalizers list includes kubernetes.io/pvc-protection:kubectl describe pvc hostpath Name: hostpath Namespace: default StorageClass: example-hostpath Status: Terminating Volume: Labels: <none> Annotations: volume.beta.kubernetes.io/storage-class=example-hostpath volume.beta.kubernetes.io/storage-provisioner=example.com/hostpath Finalizers: [kubernetes.io/pvc-protection] ... You can see that a PV is protected when the PV's status is Terminating and the Finalizers list includes kubernetes.io/pv-protection too:kubectl describe pv task-pv-volume Name: task-pv-volume Labels: type=local Annotations: <none> Finalizers: [kubernetes.io/pv-protection] StorageClass: standard Status: Terminating Claim: Reclaim Policy: Delete Access Modes: RWO Capacity: 1Gi Message: Source: Type: HostPath (bare host directory volume) Path: /tmp/data HostPathType: Events: <none> ReclaimingWhen a user is done with their volume, they can delete the PVC objects from the API that allows reclamation of the resource. The reclaim policy for a PersistentVolume tells the cluster what to do with the volume after it has been released of its claim. Currently, volumes can either be Retained, Recycled, or Deleted.RetainThe Retain reclaim policy allows for manual reclamation of the resource. When the PersistentVolumeClaim is deleted, the PersistentVolume still exists and the volume is considered "released". But it is not yet available for another claim because the previous claimant's data remains on the volume. An administrator can manually reclaim the volume with the following steps.Delete the PersistentVolume. The associated storage asset in external infrastructure still exists after the PV is deleted.Manually clean up the data on the associated storage asset accordingly.Manually delete the associated storage asset.If you want to reuse the same storage asset, create a new PersistentVolume with the same storage asset definition.DeleteFor volume plugins that support the Delete reclaim policy, deletion removes both the PersistentVolume object from Kubernetes, as well as the associated storage asset in the external infrastructure. Volumes that were dynamically provisioned inherit the reclaim policy of their StorageClass, which defaults to Delete. The administrator should configure the StorageClass according to users' expectations; otherwise, the PV must be edited or patched after it is created. See Change the Reclaim Policy of a PersistentVolume.RecycleWarning:The Recycle reclaim policy is deprecated. Instead, the recommended approach is to use dynamic provisioning.If supported by the underlying volume plugin, the Recycle reclaim policy performs a basic scrub (rm -rf /thevolume/*) on the volume and makes it available again for a new claim.However, an administrator can configure a custom recycler Pod template using the Kubernetes controller manager command line arguments as described in the reference. The custom recycler Pod template must contain a volumes specification, as shown in the example below:apiVersion: v1 kind: Pod metadata: name: pv-recycler namespace: default spec: restartPolicy: Never volumes: - name: vol hostPath: path: /any/path/it/will/be/replaced containers: - name: pv-recycler image: "registry.k8s.io/busybox" command: ["/bin/sh", "-c", "test -e /scrub && rm -rf /scrub/..?* /scrub/.[!.]* /scrub/* && test -z \"$(ls -A /scrub)\" || exit 1"] volumeMounts: - name: vol mountPath: /scrub However, the particular path specified in the custom recycler Pod template in the volumes part is replaced with the particular path of the volume that is being recycled.PersistentVolume deletion protection finalizerFEATURE STATE: Kubernetes v1.33 [stable] (enabled by default: true)Finalizers can be added on a PersistentVolume to ensure that PersistentVolumes having Delete reclaim policy are deleted only after the backing storage are deleted.The finalizer external-provisioner.volume.kubernetes.io/finalizer(introduced in v1.31) is added to both dynamically provisioned and statically provisioned CSI volumes.The finalizer kubernetes.io/pv-controller(introduced in v1.31) is added to dynamically provisioned in-tree plugin volumes and skipped for statically provisioned in-tree plugin volumes.The following is an example of dynamically provisioned in-tree plugin volume:kubectl describe pv pvc-74a498d6-3929-47e8-8c02-078c1ece4d78 Name: pvc-74a498d6-3929-47e8-8c02-078c1ece4d78 Labels: <none> Annotations: kubernetes.io/createdby: vsphere-volume-dynamic-provisioner pv.kubernetes.io/bound-by-controller: yes pv.kubernetes.io/provisioned-by: kubernetes.io/vsphere-volume Finalizers: [kubernetes.io/pv-protection kubernetes.io/pv-controller] StorageClass: vcp-sc Status: Bound Claim: default/vcp-pvc-1 Reclaim Policy: Delete Access Modes: RWO VolumeMode: Filesystem Capacity: 1Gi Node Affinity: <none> Message: Source: Type: vSphereVolume (a Persistent Disk resource in vSphere) VolumePath: [vsanDatastore] d49c4a62-166f-ce12-c464-020077ba5d46/kubernetes-dynamic-pvc-74a498d6-3929-47e8-8c02-078c1ece4d78.vmdk FSType: ext4 StoragePolicyName: vSAN Default Storage Policy Events: <none> The finalizer external-provisioner.volume.kubernetes.io/finalizer is added for CSI volumes. The following is an example:Name: pvc-2f0bab97-85a8-4552-8044-eb8be45cf48d Labels: <none> Annotations: pv.kubernetes.io/provisioned-by: csi.vsphere.vmware.com Finalizers: [kubernetes.io/pv-protection external-provisioner.volume.kubernetes.io/finalizer] StorageClass: fast Status: Bound Claim: demo-app/nginx-logs Reclaim Policy: Delete Access Modes: RWO VolumeMode: Filesystem Capacity: 200Mi Node Affinity: <none> Message: Source: Type: CSI (a Container Storage Interface (CSI) volume source) Driver: csi.vsphere.vmware.com FSType: ext4 VolumeHandle: 44830fa8-79b4-406b-8b58-621ba25353fd ReadOnly: false VolumeAttributes: storage.kubernetes.io/csiProvisionerIdentity=1648442357185-8081-csi.vsphere.vmware.com type=vSphere CNS Block Volume Events: <none> When the CSIMigration{provider} feature flag is enabled for a specific in-tree volume plugin, the kubernetes.io/pv-controller finalizer is replaced by the external-provisioner.volume.kubernetes.io/finalizer finalizer.The finalizers ensure that the PV object is removed only after the volume is deleted from the storage backend provided the reclaim policy of the PV is Delete. This also ensures that the volume is deleted from storage backend irrespective of the order of deletion of PV and PVC.Reserving a PersistentVolumeThe control plane can bind PersistentVolumeClaims to matching PersistentVolumes in the cluster. However, if you want a PVC to bind to a specific PV, you need to pre-bind them.By specifying a PersistentVolume in a PersistentVolumeClaim, you declare a binding between that specific PV and PVC. If the PersistentVolume exists and has not reserved PersistentVolumeClaims through its claimRef field, then the PersistentVolume and PersistentVolumeClaim will be bound.The binding happens regardless of some volume matching criteria, including node affinity. The control plane still checks that storage class, access modes, and requested storage size are valid.apiVersion: v1 kind: PersistentVolumeClaim metadata: name: foo-pvc namespace: foo spec: storageClassName: "" # Empty string must be explicitly set otherwise default StorageClass will be set volumeName: foo-pv ... This method does not guarantee any binding privileges to the PersistentVolume. If other PersistentVolumeClaims could use the PV that you specify, you first need to reserve that storage volume. Specify the relevant PersistentVolumeClaim in the claimRef field of the PV so that other PVCs can not bind to it.apiVersion: v1 kind: PersistentVolume metadata: name: foo-pv spec: storageClassName: "" claimRef: name: foo-pvc namespace: foo ... This is useful if you want to consume PersistentVolumes that have their persistentVolumeReclaimPolicy set to Retain, including cases where you are reusing an existing PV.Expanding Persistent Volumes ClaimsFEATURE STATE: Kubernetes v1.24 [stable]Support for expanding PersistentVolumeClaims (PVCs) is enabled by default. You can expand the following types of volumes:csi (including some CSI migrated volme types)flexVolume (deprecated)portworxVolume (deprecated)You can only expand a PVC if its storage class's allowVolumeExpansion field is set to true.apiVersion: storage.k8s.io/v1 kind: StorageClass metadata: name: example-vol-default provisioner: vendor-name.example/magicstorage parameters: resturl: "http://192.168.10.100:8080" restuser: "" secretNamespace: "" secretName: "" allowVolumeExpansion: true To request a larger volume for a PVC, edit the PVC object and specify a larger size. This triggers expansion of the volume that backs the underlying PersistentVolume. A new PersistentVolume is never created to satisfy the claim. Instead, an existing volume is resized.Warning:Directly editing the size of a PersistentVolume can prevent an automatic resize of that volume. If you edit the capacity of a PersistentVolume, and then edit the .spec of a matching PersistentVolumeClaim to make the size of the PersistentVolumeClaim match the PersistentVolume, then no storage resize happens. The Kubernetes control plane will see that the desired state of both resources matches, conclude that the backing volume size has been manually increased and that no resize is necessary.CSI Volume expansionFEATURE STATE: Kubernetes v1.24 [stable]Support for expanding CSI volumes is enabled by default but it also requires a specific CSI driver to support volume expansion. Refer to documentation of the specific CSI driver for more information.Resizing a volume containing a file systemYou can only resize volumes containing a file system if the file system is XFS, Ext3, or Ext4.When a volume contains a file system, the file system is only resized when a new Pod is using the PersistentVolumeClaim in ReadWrite mode. File system expansion is either done when a Pod is starting up or when a Pod is running and the underlying file system supports online expansion.FlexVolumes (deprecated since Kubernetes v1.23) allow resize if the driver is configured with the RequiresFSResize capability to true. The FlexVolume can be resized on Pod restart.Resizing an in-use PersistentVolumeClaimFEATURE STATE: Kubernetes v1.24 [stable]In this case, you don't need to delete and recreate a Pod or deployment that is using an existing PVC. Any in-use PVC automatically becomes available to its Pod as soon as its file system has been expanded. This feature has no effect on PVCs that are not in use by a Pod or deployment. You must create a Pod that uses the PVC before the expansion can complete.Similar to other volume types - FlexVolume volumes can also be expanded when in-use by a Pod.Note:FlexVolume resize is possible only when the underlying driver supports resize.Recovering from Failure when Expanding VolumesIf a user specifies a new size that is too big to be satisfied by underlying storage system, expansion of PVC will be continuously retried until user or cluster administrator takes some action. This can be undesirable and hence Kubernetes provides following methods of recovering from such failures.If expanding underlying storage fails, the cluster administrator can manually recover the Persistent Volume Claim (PVC) state and cancel the resize requests. Otherwise, the resize requests are continuously retried by the controller without administrator intervention.Mark the PersistentVolume(PV) that is bound to the PersistentVolumeClaim(PVC) with Retain reclaim policy.Delete the PVC. Since PV has Retain reclaim policy - we will not lose any data when we recreate the PVC.Delete the claimRef entry from PV specs, so as new PVC can bind to it. This should make the PV Available.Re-create the PVC with smaller size than PV and set volumeName field of the PVC to the name of the PV. This should bind new PVC to existing PV.Don't forget to restore the reclaim policy of the PV.If expansion has failed for a PVC, you can retry expansion with a smaller size than the previously requested value. To request a new expansion attempt with a smaller proposed size, edit .spec.resources for that PVC and choose a value that is less than the value you previously tried. This is useful if expansion to a higher value did not succeed because of capacity constraint. If that has happened, or you suspect that it might have, you can retry expansion by specifying a size that is within the capacity limits of underlying storage provider. You can monitor status of resize operation by watching .status.allocatedResourceStatuses and events on the PVC.Note that, although you can specify a lower amount of storage than what was requested previously, the new value must still be higher than .status.capacity. Kubernetes does not support shrinking a PVC to less than its current size.Types of Persistent VolumesPersistentVolume types are implemented as plugins. Kubernetes currently supports the following plugins:csi - Container Storage Interface (CSI)fc - Fibre Channel (FC) storagehostPath - HostPath volume (for single node testing only; WILL NOT WORK in a multi-node cluster; consider using local volume instead)iscsi - iSCSI (SCSI over IP) storagelocal - local storage devices mounted on nodes.nfs - Network File System (NFS) storageThe following types of PersistentVolume are deprecated but still available. If you are using these volume types except for flexVolume, cephfs and rbd, please install corresponding CSI drivers.awsElasticBlockStore - AWS Elastic Block Store (EBS) (migration on by default starting v1.23)azureDisk - Azure Disk (migration on by default starting v1.23)azureFile - Azure File (migration on by default starting v1.24)cinder - Cinder (OpenStack block storage) (migration on by default starting v1.21)flexVolume - FlexVolume (deprecated starting v1.23, no migration plan and no plan to remove support)gcePersistentDisk - GCE Persistent Disk (migration on by default starting v1.23)portworxVolume - Portworx volume (migration on by default starting v1.31)vsphereVolume - vSphere VMDK volume (migration on by default starting v1.25)Older versions of Kubernetes also supported the following in-tree PersistentVolume types:cephfs (not available starting v1.31)flocker - Flocker storage. (not available starting v1.25)glusterfs - GlusterFS storage. (not available starting v1.26)photonPersistentDisk - Photon controller persistent disk. (not available starting v1.15)quobyte - Quobyte volume. (not available starting v1.25)rbd - Rados Block Device (RBD) volume (not available starting v1.31)scaleIO - ScaleIO volume. (not available starting v1.21)storageos - StorageOS volume. (not available starting v1.25)Persistent VolumesEach PV contains a spec and status, which is the specification and status of the volume. The name of a PersistentVolume object must be a valid DNS subdomain name.apiVersion: v1 kind: PersistentVolume metadata: name: pv0003 spec: capacity: storage: 5Gi volumeMode: Filesystem accessModes: - ReadWriteOnce persistentVolumeReclaimPolicy: Recycle storageClassName: slow mountOptions: - hard - nfsvers=4.1 nfs: path: /tmp server: 172.17.0.2 Note:Helper programs relating to the volume type may be required for consumption of a PersistentVolume within a cluster. In this example, the PersistentVolume is of type NFS and the helper program /sbin/mount.nfs is required to support the mounting of NFS filesystems.CapacityGenerally, a PV will have a specific storage capacity. This is set using the PV's capacity attribute which is a Quantity value.Currently, storage size is the only resource that can be set or requested. Future attributes may include IOPS, throughput, etc.Volume ModeFEATURE STATE: Kubernetes v1.18 [stable]Kubernetes supports two volumeModes of PersistentVolumes: Filesystem and Block.volumeMode is an optional API parameter. Filesystem is the default mode used when volumeMode parameter is omitted.A volume with volumeMode: Filesystem is mounted into Pods into a directory. If the volume is backed by a block device and the device is empty, Kubernetes creates a filesystem on the device before mounting it for the first time.You can set the value of volumeMode to Block to use a volume as a raw block device. Such volume is presented into a Pod as a block device, without any filesystem on it. This mode is useful to provide a Pod the fastest possible way to access a volume, without any filesystem layer between the Pod and the volume. On the other hand, the application running in the Pod must know how to handle a raw block device. See Raw Block Volume Support for an example on how to use a volume with volumeMode: Block in a Pod.Access ModesA PersistentVolume can be mounted on a host in any way supported by the resource provider. As shown in the table below, providers will have different capabilities and each PV's access modes are set to the specific modes supported by that particular volume. For example, NFS can support multiple read/write clients, but a specific NFS PV might be exported on the server as read-only. Each PV gets its own set of access modes describing that specific PV's capabilities.The access modes are:ReadWriteOncethe volume can be mounted as read-write by a single node. ReadWriteOnce access mode still can allow multiple pods to access (read from or write to) that volume when the pods are running on the same node. For single pod access, please see ReadWriteOncePod.ReadOnlyManythe volume can be mounted as read-only by many nodes.ReadWriteManythe volume can be mounted as read-write by many nodes.ReadWriteOncePodFEATURE STATE: Kubernetes v1.29 [stable]the volume can be mounted as read-write by a single Pod. Use ReadWriteOncePod access mode if you want to ensure that only one pod across the whole cluster can read that PVC or write to it.Note:The ReadWriteOncePod access mode is only supported for CSI volumes and Kubernetes version 1.22+. To use this feature you will need to update the following CSI sidecars to these versions or greater:csi-provisioner:v3.0.0+csi-attacher:v3.3.0+csi-resizer:v1.3.0+In the CLI, the access modes are abbreviated to:RWO - ReadWriteOnceROX - ReadOnlyManyRWX - ReadWriteManyRWOP - ReadWriteOncePodNote:Kubernetes uses volume access modes to match PersistentVolumeClaims and PersistentVolumes. In some cases, the volume access modes also constrain where the PersistentVolume can be mounted. Volume access modes do not enforce write protection once the storage has been mounted. Even if the access modes are specified as ReadWriteOnce, ReadOnlyMany, or ReadWriteMany, they don't set any constraints on the volume. For example, even if a PersistentVolume is created as ReadOnlyMany, it is no guarantee that it will be read-only. If the access modes are specified as ReadWriteOncePod, the volume is constrained and can be mounted on only a single Pod.Important! A volume can only be mounted using one access mode at a time, even if it supports many.Volume PluginReadWriteOnceReadOnlyManyReadWriteManyReadWriteOncePodAzureFile✓✓✓-CephFS✓✓✓-CSIdepends on the driverdepends on the driverdepends on the driverdepends on the driverFC✓✓--FlexVolume✓✓depends on the driver-HostPath✓---iSCSI✓✓--NFS✓✓✓-RBD✓✓--VsphereVolume✓-- (works when Pods are collocated)-PortworxVolume✓-✓-ClassA PV can have a class, which is specified by setting the storageClassName attribute to the name of a StorageClass. A PV of a particular class can only be bound to PVCs requesting that class. A PV with no storageClassName has no class and can only be bound to PVCs that request no particular class.In the past, the annotation volume.beta.kubernetes.io/storage-class was used instead of the storageClassName attribute. This annotation is still working; however, it will become fully deprecated in a future Kubernetes release.Reclaim PolicyCurrent reclaim policies are:Retain -- manual reclamationRecycle -- basic scrub (rm -rf /thevolume/*)Delete -- delete the volumeFor Kubernetes 1.34, only nfs and hostPath volume types support recycling.Mount OptionsA Kubernetes administrator can specify additional mount options for when a Persistent Volume is mounted on a node.Note:Not all Persistent Volume types support mount options.The following volume types support mount options:csi (including CSI migrated volume types)iscsinfsMount options are not validated. If a mount option is invalid, the mount fails.In the past, the annotation volume.beta.kubernetes.io/mount-options was used instead of the mountOptions attribute. This annotation is still working; however, it will become fully deprecated in a future Kubernetes release.Node AffinityNote:For most volume types, you do not need to set this field. You need to explicitly set this for local volumes.A PV can specify node affinity to define constraints that limit what nodes this volume can be accessed from. Pods that use a PV will only be scheduled to nodes that are selected by the node affinity. To specify node affinity, set nodeAffinity in the .spec of a PV. The PersistentVolume API reference has more details on this field.PhaseA PersistentVolume will be in one of the following phases:Availablea free resource that is not yet bound to a claimBoundthe volume is bound to a claimReleasedthe claim has been deleted, but the associated storage resource is not yet reclaimed by the clusterFailedthe volume has failed its (automated) reclamationYou can see the name of the PVC bound to the PV using kubectl describe persistentvolume <name>.Phase transition timestampFEATURE STATE: Kubernetes v1.31 [stable] (enabled by default: true)The .status field for a PersistentVolume can include an alpha lastPhaseTransitionTime field. This field records the timestamp of when the volume last transitioned its phase. For newly created volumes the phase is set to Pending and lastPhaseTransitionTime is set to the current time.PersistentVolumeClaimsEach PVC contains a spec and status, which is the specification and status of the claim. The name of a PersistentVolumeClaim object must be a valid DNS subdomain name.apiVersion: v1 kind: PersistentVolumeClaim metadata: name: myclaim spec: accessModes: - ReadWriteOnce volumeMode: Filesystem resources: requests: storage: 8Gi storageClassName: slow selector: matchLabels: release: "stable" matchExpressions: - {key: environment, operator: In, values: [dev]} Access ModesClaims use the same conventions as volumes when requesting storage with specific access modes.Volume ModesClaims use the same convention as volumes to indicate the consumption of the volume as either a filesystem or block device.Volume NameClaims can use the volumeName field to explicitly bind to a specific PersistentVolume. You can also leave volumeName unset, indicating that you'd like Kubernetes to set up a new PersistentVolume that matches the claim. If the specified PV is already bound to another PVC, the binding will be stuck in a pending state.ResourcesClaims, like Pods, can request specific quantities of a resource. In this case, the request is for storage. The same resource model applies to both volumes and claims.Note:For Filesystem volumes, the storage request refers to the "outer" volume size (i.e. the allocated size from the storage backend). This means that the writeable size may be slightly lower for providers that build a filesystem on top of a block device, due to filesystem overhead. This is especially visible with XFS, where many metadata features are enabled by default.SelectorClaims can specify a label selector to further filter the set of volumes. Only the volumes whose labels match the selector can be bound to the claim. The selector can consist of two fields:matchLabels - the volume must have a label with this valuematchExpressions - a list of requirements made by specifying key, list of values, and operator that relates the key and values. Valid operators include In, NotIn, Exists, and DoesNotExist.All of the requirements, from both matchLabels and matchExpressions, are ANDed together – they must all be satisfied in order to match.ClassA claim can request a particular class by specifying the name of a StorageClass using the attribute storageClassName. Only PVs of the requested class, ones with the same storageClassName as the PVC, can be bound to the PVC.PVCs don't necessarily have to request a class. A PVC with its storageClassName set equal to "" is always interpreted to be requesting a PV with no class, so it can only be bound to PVs with no class (no annotation or one set equal to ""). A PVC with no storageClassName is not quite the same and is treated differently by the cluster, depending on whether the DefaultStorageClass admission plugin is turned on.If the admission plugin is turned on, the administrator may specify a default StorageClass. All PVCs that have no storageClassName can be bound only to PVs of that default. Specifying a default StorageClass is done by setting the annotation storageclass.kubernetes.io/is-default-class equal to true in a StorageClass object. If the administrator does not specify a default, the cluster responds to PVC creation as if the admission plugin were turned off. If more than one default StorageClass is specified, the newest default is used when the PVC is dynamically provisioned.If the admission plugin is turned off, there is no notion of a default StorageClass. All PVCs that have storageClassName set to "" can be bound only to PVs that have storageClassName also set to "". However, PVCs with missing storageClassName can be updated later once default StorageClass becomes available. If the PVC gets updated it will no longer bind to PVs that have storageClassName also set to "".See retroactive default StorageClass assignment for more details.Depending on installation method, a default StorageClass may be deployed to a Kubernetes cluster by addon manager during installation.When a PVC specifies a selector in addition to requesting a StorageClass, the requirements are ANDed together: only a PV of the requested class and with the requested labels may be bound to the PVC.Note:Currently, a PVC with a non-empty selector can't have a PV dynamically provisioned for it.In the past, the annotation volume.beta.kubernetes.io/storage-class was used instead of storageClassName attribute. This annotation is still working; however, it won't be supported in a future Kubernetes release.Retroactive default StorageClass assignmentFEATURE STATE: Kubernetes v1.28 [stable]You can create a PersistentVolumeClaim without specifying a storageClassName for the new PVC, and you can do so even when no default StorageClass exists in your cluster. In this case, the new PVC creates as you defined it, and the storageClassName of that PVC remains unset until default becomes available.When a default StorageClass becomes available, the control plane identifies any existing PVCs without storageClassName. For the PVCs that either have an empty value for storageClassName or do not have this key, the control plane then updates those PVCs to set storageClassName to match the new default StorageClass. If you have an existing PVC where the storageClassName is "", and you configure a default StorageClass, then this PVC will not get updated.In order to keep binding to PVs with storageClassName set to "" (while a default StorageClass is present), you need to set the storageClassName of the associated PVC to "".This behavior helps administrators change default StorageClass by removing the old one first and then creating or setting another one. This brief window while there is no default causes PVCs without storageClassName created at that time to not have any default, but due to the retroactive default StorageClass assignment this way of changing defaults is safe.Claims As VolumesPods access storage by using the claim as a volume. Claims must exist in the same namespace as the Pod using the claim. The cluster finds the claim in the Pod's namespace and uses it to get the PersistentVolume backing the claim. The volume is then mounted to the host and into the Pod.apiVersion: v1 kind: Pod metadata: name: mypod spec: containers: - name: myfrontend image: nginx volumeMounts: - mountPath: "/var/www/html" name: mypd volumes: - name: mypd persistentVolumeClaim: claimName: myclaim A Note on NamespacesPersistentVolumes binds are exclusive, and since PersistentVolumeClaims are namespaced objects, mounting claims with "Many" modes (ROX, RWX) is only possible within one namespace.PersistentVolumes typed hostPathA hostPath PersistentVolume uses a file or directory on the Node to emulate network-attached storage. See an example of hostPath typed volume.Raw Block Volume SupportFEATURE STATE: Kubernetes v1.18 [stable]The following volume plugins support raw block volumes, including dynamic provisioning where applicable:CSI (including some CSI migrated volume types)FC (Fibre Channel)iSCSILocal volumePersistentVolume using a Raw Block VolumeapiVersion: v1 kind: PersistentVolume metadata: name: block-pv spec: capacity: storage: 10Gi accessModes: - ReadWriteOnce volumeMode: Block persistentVolumeReclaimPolicy: Retain fc: targetWWNs: ["50060e801049cfd1"] lun: 0 readOnly: false PersistentVolumeClaim requesting a Raw Block VolumeapiVersion: v1 kind: PersistentVolumeClaim metadata: name: block-pvc spec: accessModes: - ReadWriteOnce volumeMode: Block resources: requests: storage: 10Gi Pod specification adding Raw Block Device path in containerapiVersion: v1 kind: Pod metadata: name: pod-with-block-volume spec: containers: - name: fc-container image: fedora:26 command: ["/bin/sh", "-c"] args: [ "tail -f /dev/null" ] volumeDevices: - name: data devicePath: /dev/xvda volumes: - name: data persistentVolumeClaim: claimName: block-pvc Note:When adding a raw block device for a Pod, you specify the device path in the container instead of a mount path.Binding Block VolumesIf a user requests a raw block volume by indicating this using the volumeMode field in the PersistentVolumeClaim spec, the binding rules differ slightly from previous releases that didn't consider this mode as part of the spec. Listed is a table of possible combinations the user and admin might specify for requesting a raw block device. The table indicates if the volume will be bound or not given the combinations: Volume binding matrix for statically provisioned volumes:PV volumeModePVC volumeModeResultunspecifiedunspecifiedBINDunspecifiedBlockNO BINDunspecifiedFilesystemBINDBlockunspecifiedNO BINDBlockBlockBINDBlockFilesystemNO BINDFilesystemFilesystemBINDFilesystemBlockNO BINDFilesystemunspecifiedBINDNote:Only statically provisioned volumes are supported for alpha release. Administrators should take care to consider these values when working with raw block devices.Volume Snapshot and Restore Volume from Snapshot SupportFEATURE STATE: Kubernetes v1.20 [stable]Volume snapshots only support the out-of-tree CSI volume plugins. For details, see Volume Snapshots. In-tree volume plugins are deprecated. You can read about the deprecated volume plugins in the Volume Plugin FAQ.Create a PersistentVolumeClaim from a Volume SnapshotapiVersion: v1 kind: PersistentVolumeClaim metadata: name: restore-pvc spec: storageClassName: csi-hostpath-sc dataSource: name: new-snapshot-test kind: VolumeSnapshot apiGroup: snapshot.storage.k8s.io accessModes: - ReadWriteOnce resources: requests: storage: 10Gi Volume CloningVolume Cloning only available for CSI volume plugins.Create PersistentVolumeClaim from an existing PVCapiVersion: v1 kind: PersistentVolumeClaim metadata: name: cloned-pvc spec: storageClassName: my-csi-plugin dataSource: name: existing-src-pvc-name kind: PersistentVolumeClaim accessModes: - ReadWriteOnce resources: requests: storage: 10Gi Volume populators and data sourcesFEATURE STATE: Kubernetes v1.24 [beta]Kubernetes supports custom volume populators. To use custom volume populators, you must enable the AnyVolumeDataSource feature gate for the kube-apiserver and kube-controller-manager.Volume populators take advantage of a PVC spec field called dataSourceRef. Unlike the dataSource field, which can only contain either a reference to another PersistentVolumeClaim or to a VolumeSnapshot, the dataSourceRef field can contain a reference to any object in the same namespace, except for core objects other than PVCs. For clusters that have the feature gate enabled, use of the dataSourceRef is preferred over dataSource.Cross namespace data sourcesFEATURE STATE: Kubernetes v1.26 [alpha]Kubernetes supports cross namespace volume data sources. To use cross namespace volume data sources, you must enable the AnyVolumeDataSource and CrossNamespaceVolumeDataSource feature gates for the kube-apiserver and kube-controller-manager. Also, you must enable the CrossNamespaceVolumeDataSource feature gate for the csi-provisioner.Enabling the CrossNamespaceVolumeDataSource feature gate allows you to specify a namespace in the dataSourceRef field.Note:When you specify a namespace for a volume data source, Kubernetes checks for a ReferenceGrant in the other namespace before accepting the reference. ReferenceGrant is part of the gateway.networking.k8s.io extension APIs. See ReferenceGrant in the Gateway API documentation for details. This means that you must extend your Kubernetes cluster with at least ReferenceGrant from the Gateway API before you can use this mechanism.Data source referencesThe dataSourceRef field behaves almost the same as the dataSource field. If one is specified while the other is not, the API server will give both fields the same value. Neither field can be changed after creation, and attempting to specify different values for the two fields will result in a validation error. Therefore the two fields will always have the same contents.There are two differences between the dataSourceRef field and the dataSource field that users should be aware of:The dataSource field ignores invalid values (as if the field was blank) while the dataSourceRef field never ignores values and will cause an error if an invalid value is used. Invalid values are any core object (objects with no apiGroup) except for PVCs.The dataSourceRef field may contain different types of objects, while the dataSource field only allows PVCs and VolumeSnapshots.When the CrossNamespaceVolumeDataSource feature is enabled, there are additional differences:The dataSource field only allows local objects, while the dataSourceRef field allows objects in any namespaces.When namespace is specified, dataSource and dataSourceRef are not synced.Users should always use dataSourceRef on clusters that have the feature gate enabled, and fall back to dataSource on clusters that do not. It is not necessary to look at both fields under any circumstance. The duplicated values with slightly different semantics exist only for backwards compatibility. In particular, a mixture of older and newer controllers are able to interoperate because the fields are the same.Using volume populatorsVolume populators are controllers that can create non-empty volumes, where the contents of the volume are determined by a Custom Resource. Users create a populated volume by referring to a Custom Resource using the dataSourceRef field:apiVersion: v1 kind: PersistentVolumeClaim metadata: name: populated-pvc spec: dataSourceRef: name: example-name kind: ExampleDataSource apiGroup: example.storage.k8s.io accessModes: - ReadWriteOnce resources: requests: storage: 10Gi Because volume populators are external components, attempts to create a PVC that uses one can fail if not all the correct components are installed. External controllers should generate events on the PVC to provide

Persistent Volumes


Image Policy API (v1alpha1)Resource TypesImageReviewImageReviewImageReview checks if the set of images in a pod are allowed.FieldDescriptionapiVersionstringimagepolicy.k8s.io/v1alpha1kindstringImageReviewmetadatameta/v1.ObjectMetaStandard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadataRefer to the Kubernetes API documentation for the fields of the metadata field.spec [Required]ImageReviewSpecSpec holds information about the pod being evaluatedstatusImageReviewStatusStatus is filled in by the backend and indicates whether the pod should be allowed.ImageReviewContainerSpecAppears in:ImageReviewSpecImageReviewContainerSpec is a description of a container within the pod creation request.FieldDescriptionimagestringThis can be in the form image:tag or image@SHA:012345679abcdef.ImageReviewSpecAppears in:ImageReviewImageReviewSpec is a description of the pod creation request.FieldDescriptioncontainers[]ImageReviewContainerSpecContainers is a list of a subset of the information in each container of the Pod being created.annotationsmap[string]stringAnnotations is a list of key-value pairs extracted from the Pod's annotations. It only includes keys which match the pattern *.image-policy.k8s.io/*. It is up to each webhook backend to determine how to interpret these annotations, if at all.namespacestringNamespace is the namespace the pod is being created in.ImageReviewStatusAppears in:ImageReviewImageReviewStatus is the result of the review for the pod creation request.FieldDescriptionallowed [Required]boolAllowed indicates that all images were allowed to be run.reasonstringReason should be empty unless Allowed is false in which case it may contain a short description of what is wrong. Kubernetes may truncate excessively long errors when displaying to the user.auditAnnotationsmap[string]stringAuditAnnotations will be added to the attributes object of the admission controller request using 'AddAnnotation'. The keys should be prefix-less (i.e., the admission controller will add an appropriate prefix).This page is automatically generated.If you plan to report an issue with this page, mention that the page is auto-generated in your issue description. The fix may need to happen elsewhere in the Kubernetes project.

Image Policy API (v1alpha1)


Workload ManagementKubernetes provides several built-in APIs for declarative management of your workloads and the components of those workloads.Ultimately, your applications run as containers inside Pods; however, managing individual Pods would be a lot of effort. For example, if a Pod fails, you probably want to run a new Pod to replace it. Kubernetes can do that for you.You use the Kubernetes API to create a workload object that represents a higher abstraction level than a Pod, and then the Kubernetes control plane automatically manages Pod objects on your behalf, based on the specification for the workload object you defined.The built-in APIs for managing workloads are:Deployment (and, indirectly, ReplicaSet), the most common way to run an application on your cluster. Deployment is a good fit for managing a stateless application workload on your cluster, where any Pod in the Deployment is interchangeable and can be replaced if needed. (Deployments are a replacement for the legacy ReplicationController API).A StatefulSet lets you manage one or more Pods – all running the same application code – where the Pods rely on having a distinct identity. This is different from a Deployment where the Pods are expected to be interchangeable. The most common use for a StatefulSet is to be able to make a link between its Pods and their persistent storage. For example, you can run a StatefulSet that associates each Pod with a PersistentVolume. If one of the Pods in the StatefulSet fails, Kubernetes makes a replacement Pod that is connected to the same PersistentVolume.A DaemonSet defines Pods that provide facilities that are local to a specific node; for example, a driver that lets containers on that node access a storage system. You use a DaemonSet when the driver, or other node-level service, has to run on the node where it's useful. Each Pod in a DaemonSet performs a role similar to a system daemon on a classic Unix / POSIX server. A DaemonSet might be fundamental to the operation of your cluster, such as a plugin to let that node access cluster networking, it might help you to manage the node, or it could provide less essential facilities that enhance the container platform you are running. You can run DaemonSets (and their pods) across every node in your cluster, or across just a subset (for example, only install the GPU accelerator driver on nodes that have a GPU installed).You can use a Job and / or a CronJob to define tasks that run to completion and then stop. A Job represents a one-off task, whereas each CronJob repeats according to a schedule.Other topics in this section:Automatic Cleanup for Finished JobsReplicationController

Workload Management


Organizing Cluster Access Using kubeconfig FilesUse kubeconfig files to organize information about clusters, users, namespaces, and authentication mechanisms. The kubectl command-line tool uses kubeconfig files to find the information it needs to choose a cluster and communicate with the API server of a cluster.Note:A file that is used to configure access to clusters is called a kubeconfig file. This is a generic way of referring to configuration files. It does not mean that there is a file named kubeconfig.Warning:Only use kubeconfig files from trusted sources. Using a specially-crafted kubeconfig file could result in malicious code execution or file exposure. If you must use an untrusted kubeconfig file, inspect it carefully first, much as you would a shell script.By default, kubectl looks for a file named config in the $HOME/.kube directory. You can specify other kubeconfig files by setting the KUBECONFIG environment variable or by setting the --kubeconfig flag.For step-by-step instructions on creating and specifying kubeconfig files, see Configure Access to Multiple Clusters.Supporting multiple clusters, users, and authentication mechanismsSuppose you have several clusters, and your users and components authenticate in a variety of ways. For example:A running kubelet might authenticate using certificates.A user might authenticate using tokens.Administrators might have sets of certificates that they provide to individual users.With kubeconfig files, you can organize your clusters, users, and namespaces. You can also define contexts to quickly and easily switch between clusters and namespaces.ContextA context element in a kubeconfig file is used to group access parameters under a convenient name. Each context has three parameters: cluster, namespace, and user. By default, the kubectl command-line tool uses parameters from the current context to communicate with the cluster.To choose the current context:kubectl config use-context The KUBECONFIG environment variableThe KUBECONFIG environment variable holds a list of kubeconfig files. For Linux and Mac, the list is colon-delimited. For Windows, the list is semicolon-delimited. The KUBECONFIG environment variable is not required. If the KUBECONFIG environment variable doesn't exist, kubectl uses the default kubeconfig file, $HOME/.kube/config.If the KUBECONFIG environment variable does exist, kubectl uses an effective configuration that is the result of merging the files listed in the KUBECONFIG environment variable.Merging kubeconfig filesTo see your configuration, enter this command:kubectl config view As described previously, the output might be from a single kubeconfig file, or it might be the result of merging several kubeconfig files.Here are the rules that kubectl uses when it merges kubeconfig files:If the --kubeconfig flag is set, use only the specified file. Do not merge. Only one instance of this flag is allowed.Otherwise, if the KUBECONFIG environment variable is set, use it as a list of files that should be merged. Merge the files listed in the KUBECONFIG environment variable according to these rules:Ignore empty filenames.Produce errors for files with content that cannot be deserialized.The first file to set a particular value or map key wins.Never change the value or map key. Example: Preserve the context of the first file to set current-context. Example: If two files specify a red-user, use only values from the first file's red-user. Even if the second file has non-conflicting entries under red-user, discard them.For an example of setting the KUBECONFIG environment variable, see Setting the KUBECONFIG environment variable.Otherwise, use the default kubeconfig file, $HOME/.kube/config, with no merging.Determine the context to use based on the first hit in this chain:Use the --context command-line flag if it exists.Use the current-context from the merged kubeconfig files.An empty context is allowed at this point.Determine the cluster and user. At this point, there might or might not be a context. Determine the cluster and user based on the first hit in this chain, which is run twice: once for user and once for cluster:Use a command-line flag if it exists: --user or --cluster.If the context is non-empty, take the user or cluster from the context.The user and cluster can be empty at this point.Determine the actual cluster information to use. At this point, there might or might not be cluster information. Build each piece of the cluster information based on this chain; the first hit wins:Use command line flags if they exist: --server, --certificate-authority, --insecure-skip-tls-verify.If any cluster information attributes exist from the merged kubeconfig files, use them.If there is no server location, fail.Determine the actual user information to use. Build user information using the same rules as cluster information, except allow only one authentication technique per user:Use command line flags if they exist: --client-certificate, --client-key, --username, --password, --token.Use the user fields from the merged kubeconfig files.If there are two conflicting techniques, fail.For any information still missing, use default values and potentially prompt for authentication information.File referencesFile and path references in a kubeconfig file are relative to the location of the kubeconfig file. File references on the command line are relative to the current working directory. In $HOME/.kube/config, relative paths are stored relatively, and absolute paths are stored absolutely.ProxyYou can configure kubectl to use a proxy per cluster using proxy-url in your kubeconfig file, like this:apiVersion: v1 kind: Config clusters: - cluster: proxy-url: http://proxy.example.org:3128 server: https://k8s.example.org/k8s/clusters/c-xxyyzz name: development users: - name: developer contexts: - context: name: development What's nextConfigure Access to Multiple Clusterskubectl config


Resource Management for Windows nodesThis page outlines the differences in how resources are managed between Linux and Windows.On Linux nodes, cgroups are used as a pod boundary for resource control. Containers are created within that boundary for network, process and file system isolation. The Linux cgroup APIs can be used to gather CPU, I/O, and memory use statistics.In contrast, Windows uses a job object per container with a system namespace filter to contain all processes in a container and provide logical isolation from the host. (Job objects are a Windows process isolation mechanism and are different from what Kubernetes refers to as a Job).There is no way to run a Windows container without the namespace filtering in place. This means that system privileges cannot be asserted in the context of the host, and thus privileged containers are not available on Windows. Containers cannot assume an identity from the host because the Security Account Manager (SAM) is separate.Memory managementWindows does not have an out-of-memory process killer as Linux does. Windows always treats all user-mode memory allocations as virtual, and pagefiles are mandatory.Windows nodes do not overcommit memory for processes. The net effect is that Windows won't reach out of memory conditions the same way Linux does, and processes page to disk instead of being subject to out of memory (OOM) termination. If memory is over-provisioned and all physical memory is exhausted, then paging can slow down performance.CPU managementWindows can limit the amount of CPU time allocated for different processes but cannot guarantee a minimum amount of CPU time.On Windows, the kubelet supports a command-line flag to set the scheduling priority of the kubelet process: --windows-priorityclass. This flag allows the kubelet process to get more CPU time slices when compared to other processes running on the Windows host. More information on the allowable values and their meaning is available at Windows Priority Classes. To ensure that running Pods do not starve the kubelet of CPU cycles, set this flag to ABOVE_NORMAL_PRIORITY_CLASS or above.Resource reservationTo account for memory and CPU used by the operating system, the container runtime, and by Kubernetes host processes such as the kubelet, you can (and should) reserve memory and CPU resources with the --kube-reserved and/or --system-reserved kubelet flags. On Windows these values are only used to calculate the node's allocatable resources.Caution:As you deploy workloads, set resource memory and CPU limits on containers. This also subtracts from NodeAllocatable and helps the cluster-wide scheduler in determining which pods to place on which nodes.Scheduling pods without limits may over-provision the Windows nodes and in extreme cases can cause the nodes to become unhealthy.On Windows, a good practice is to reserve at least 2GiB of memory.To determine how much CPU to reserve, identify the maximum pod density for each node and monitor the CPU usage of the system services running there, then choose a value that meets your workload needs.

Resource Management for Windows nodes


Tools for Monitoring ResourcesTo scale an application and provide a reliable service, you need to understand how the application behaves when it is deployed. You can examine application performance in a Kubernetes cluster by examining the containers, pods, services, and the characteristics of the overall cluster. Kubernetes provides detailed information about an application's resource usage at each of these levels. This information allows you to evaluate your application's performance and where bottlenecks can be removed to improve overall performance.In Kubernetes, application monitoring does not depend on a single monitoring solution. On new clusters, you can use resource metrics or full metrics pipelines to collect monitoring statistics.Resource metrics pipelineThe resource metrics pipeline provides a limited set of metrics related to cluster components such as the Horizontal Pod Autoscaler controller, as well as the kubectl top utility. These metrics are collected by the lightweight, short-term, in-memory metrics-server and are exposed via the metrics.k8s.io API.metrics-server discovers all nodes on the cluster and queries each node's kubelet for CPU and memory usage. The kubelet acts as a bridge between the Kubernetes master and the nodes, managing the pods and containers running on a machine. The kubelet translates each pod into its constituent containers and fetches individual container usage statistics from the container runtime through the container runtime interface. If you use a container runtime that uses Linux cgroups and namespaces to implement containers, and the container runtime does not publish usage statistics, then the kubelet can look up those statistics directly (using code from cAdvisor). No matter how those statistics arrive, the kubelet then exposes the aggregated pod resource usage statistics through the metrics-server Resource Metrics API. This API is served at /metrics/resource/v1beta1 on the kubelet's authenticated and read-only ports.Full metrics pipelineA full metrics pipeline gives you access to richer metrics. Kubernetes can respond to these metrics by automatically scaling or adapting the cluster based on its current state, using mechanisms such as the Horizontal Pod Autoscaler. The monitoring pipeline fetches metrics from the kubelet and then exposes them to Kubernetes via an adapter by implementing either the custom.metrics.k8s.io or external.metrics.k8s.io API.Kubernetes is designed to work with OpenMetrics, which is one of the CNCF Observability and Analysis - Monitoring Projects, built upon and carefully extending Prometheus exposition format in almost 100% backwards-compatible ways.If you glance over at the CNCF Landscape, you can see a number of monitoring projects that can work with Kubernetes by scraping metric data and using that to help you observe your cluster. It is up to you to select the tool or tools that suit your needs. The CNCF landscape for observability and analytics includes a mix of open-source software, paid-for software-as-a-service, and other commercial products.When you design and implement a full metrics pipeline you can make that monitoring data available back to Kubernetes. For example, a HorizontalPodAutoscaler can use the processed metrics to work out how many Pods to run for a component of your workload.Integration of a full metrics pipeline into your Kubernetes implementation is outside the scope of Kubernetes documentation because of the very wide scope of possible solutions.The choice of monitoring platform depends heavily on your needs, budget, and technical resources. Kubernetes does not recommend any specific metrics pipeline; many options are available. Your monitoring system should be capable of handling the OpenMetrics metrics transmission standard and needs to be chosen to best fit into your overall design and deployment of your infrastructure platform.What's nextLearn about additional debugging tools, including:LoggingGetting into containers via execConnecting to containers via proxiesConnecting to containers via port forwardingInspect Kubernetes node with crictl

Tools for Monitoring Resources


Garbage CollectionGarbage collection is a collective term for the various mechanisms Kubernetes uses to clean up cluster resources. This allows the clean up of resources like the following:Terminated podsCompleted JobsObjects without owner referencesUnused containers and container imagesDynamically provisioned PersistentVolumes with a StorageClass reclaim policy of DeleteStale or expired CertificateSigningRequests (CSRs)Nodes deleted in the following scenarios:On a cloud when the cluster uses a cloud controller managerOn-premises when the cluster uses an addon similar to a cloud controller managerNode Lease objectsOwners and dependentsMany objects in Kubernetes link to each other through owner references. Owner references tell the control plane which objects are dependent on others. Kubernetes uses owner references to give the control plane, and other API clients, the opportunity to clean up related resources before deleting an object. In most cases, Kubernetes manages owner references automatically.Ownership is different from the labels and selectors mechanism that some resources also use. For example, consider a Service that creates EndpointSlice objects. The Service uses labels to allow the control plane to determine which EndpointSlice objects are used for that Service. In addition to the labels, each EndpointSlice that is managed on behalf of a Service has an owner reference. Owner references help different parts of Kubernetes avoid interfering with objects they don’t control.Note:Cross-namespace owner references are disallowed by design. Namespaced dependents can specify cluster-scoped or namespaced owners. A namespaced owner must exist in the same namespace as the dependent. If it does not, the owner reference is treated as absent, and the dependent is subject to deletion once all owners are verified absent.Cluster-scoped dependents can only specify cluster-scoped owners. In v1.20+, if a cluster-scoped dependent specifies a namespaced kind as an owner, it is treated as having an unresolvable owner reference, and is not able to be garbage collected.In v1.20+, if the garbage collector detects an invalid cross-namespace ownerReference, or a cluster-scoped dependent with an ownerReference referencing a namespaced kind, a warning Event with a reason of OwnerRefInvalidNamespace and an involvedObject of the invalid dependent is reported. You can check for that kind of Event by running kubectl get events -A --field-selector=reason=OwnerRefInvalidNamespace.Cascading deletionKubernetes checks for and deletes objects that no longer have owner references, like the pods left behind when you delete a ReplicaSet. When you delete an object, you can control whether Kubernetes deletes the object's dependents automatically, in a process called cascading deletion. There are two types of cascading deletion, as follows:Foreground cascading deletionBackground cascading deletionYou can also control how and when garbage collection deletes resources that have owner references using Kubernetes finalizers.Foreground cascading deletionIn foreground cascading deletion, the owner object you're deleting first enters a deletion in progress state. In this state, the following happens to the owner object:The Kubernetes API server sets the object's metadata.deletionTimestamp field to the time the object was marked for deletion.The Kubernetes API server also sets the metadata.finalizers field to foregroundDeletion.The object remains visible through the Kubernetes API until the deletion process is complete.After the owner object enters the deletion in progress state, the controller deletes dependents it knows about. After deleting all the dependent objects it knows about, the controller deletes the owner object. At this point, the object is no longer visible in the Kubernetes API.During foreground cascading deletion, the only dependents that block owner deletion are those that have the ownerReference.blockOwnerDeletion=true field and are in the garbage collection controller cache. The garbage collection controller cache may not contain objects whose resource type cannot be listed / watched successfully, or objects that are created concurrent with deletion of an owner object. See Use foreground cascading deletion to learn more.Background cascading deletionIn background cascading deletion, the Kubernetes API server deletes the owner object immediately and the garbage collector controller (custom or default) cleans up the dependent objects in the background. If a finalizer exists, it ensures that objects are not deleted until all necessary clean-up tasks are completed. By default, Kubernetes uses background cascading deletion unless you manually use foreground deletion or choose to orphan the dependent objects.See Use background cascading deletion to learn more.Orphaned dependentsWhen Kubernetes deletes an owner object, the dependents left behind are called orphan objects. By default, Kubernetes deletes dependent objects. To learn how to override this behaviour, see Delete owner objects and orphan dependents.Garbage collection of unused containers and imagesThe kubelet performs garbage collection on unused images every five minutes and on unused containers every minute. You should avoid using external garbage collection tools, as these can break the kubelet behavior and remove containers that should exist.To configure options for unused container and image garbage collection, tune the kubelet using a configuration file and change the parameters related to garbage collection using the KubeletConfiguration resource type.Container image lifecycleKubernetes manages the lifecycle of all images through its image manager, which is part of the kubelet, with the cooperation of cadvisor. The kubelet considers the following disk usage limits when making garbage collection decisions:HighThresholdPercentLowThresholdPercentDisk usage above the configured HighThresholdPercent value triggers garbage collection, which deletes images in order based on the last time they were used, starting with the oldest first. The kubelet deletes images until disk usage reaches the LowThresholdPercent value.Garbage collection for unused container imagesFEATURE STATE: Kubernetes v1.30 [beta] (enabled by default: true)As a beta feature, you can specify the maximum time a local image can be unused for, regardless of disk usage. This is a kubelet setting that you configure for each node.To configure the setting, you need to set a value for the imageMaximumGCAge field in the kubelet configuration file.The value is specified as a Kubernetes duration. See duration in the glossary for more details.For example, you can set the configuration field to 12h45m, which means 12 hours and 45 minutes.Note:This feature does not track image usage across kubelet restarts. If the kubelet is restarted, the tracked image age is reset, causing the kubelet to wait the full imageMaximumGCAge duration before qualifying images for garbage collection based on image age.Container garbage collectionThe kubelet garbage collects unused containers based on the following variables, which you can define:MinAge: the minimum age at which the kubelet can garbage collect a container. Disable by setting to 0.MaxPerPodContainer: the maximum number of dead containers each Pod can have. Disable by setting to less than 0.MaxContainers: the maximum number of dead containers the cluster can have. Disable by setting to less than 0.In addition to these variables, the kubelet garbage collects unidentified and deleted containers, typically starting with the oldest first.MaxPerPodContainer and MaxContainers may potentially conflict with each other in situations where retaining the maximum number of containers per Pod (MaxPerPodContainer) would go outside the allowable total of global dead containers (MaxContainers). In this situation, the kubelet adjusts MaxPerPodContainer to address the conflict. A worst-case scenario would be to downgrade MaxPerPodContainer to 1 and evict the oldest containers. Additionally, containers owned by pods that have been deleted are removed once they are older than MinAge.Note:The kubelet only garbage collects the containers it manages.Configuring garbage collectionYou can tune garbage collection of resources by configuring options specific to the controllers managing those resources. The following pages show you how to configure garbage collection:Configuring cascading deletion of Kubernetes objectsConfiguring cleanup of finished JobsWhat's nextLearn more about ownership of Kubernetes objects.Learn more about Kubernetes finalizers.Learn about the TTL controller that cleans up finished Jobs.

Garbage Collection


Parallel Processing using ExpansionsThis task demonstrates running multiple Jobs based on a common template. You can use this approach to process batches of work in parallel.For this example there are only three items: apple, banana, and cherry. The sample Jobs process each item by printing a string then pausing.See using Jobs in real workloads to learn about how this pattern fits more realistic use cases.Before you beginYou should be familiar with the basic, non-parallel, use of Job.You need to have a Kubernetes cluster, and the kubectl command-line tool must be configured to communicate with your cluster. It is recommended to run this tutorial on a cluster with at least two nodes that are not acting as control plane hosts. If you do not already have a cluster, you can create one by using minikube or you can use one of these Kubernetes playgrounds:iximiuz LabsKillercodaKodeKloudPlay with KubernetesFor basic templating you need the command-line utility sed.To follow the advanced templating example, you need a working installation of Python, and the Jinja2 template library for Python.Once you have Python set up, you can install Jinja2 by running:pip install --user jinja2 Create Jobs based on a templateFirst, download the following template of a Job to a file called job-tmpl.yaml. Here's what you'll download:application/job/job-tmpl.yaml apiVersion: batch/v1 kind: Job metadata: name: process-item-$ITEM labels: jobgroup: jobexample spec: template: metadata: name: jobexample labels: jobgroup: jobexample spec: containers: - name: c image: busybox:1.28 command: ["sh", "-c", "echo Processing item $ITEM && sleep 5"] restartPolicy: Never # Use curl to download job-tmpl.yaml curl -L -s -O https://k8s.io/examples/application/job/job-tmpl.yaml The file you downloaded is not yet a valid Kubernetes manifest. Instead that template is a YAML representation of a Job object with some placeholders that need to be filled in before it can be used. The $ITEM syntax is not meaningful to Kubernetes.Create manifests from the templateThe following shell snippet uses sed to replace the string $ITEM with the loop variable, writing into a temporary directory named jobs. Run this now:# Expand the template into multiple files, one for each item to be processed. mkdir ./jobs for i in apple banana cherry do cat job-tmpl.yaml | sed "s/\$ITEM/$i/" > ./jobs/job-$i.yaml done Check if it worked:ls jobs/ The output is similar to this:job-apple.yaml job-banana.yaml job-cherry.yaml You could use any type of template language (for example: Jinja2; ERB), or write a program to generate the Job manifests.Create Jobs from the manifestsNext, create all the Jobs with one kubectl command:kubectl create -f ./jobs The output is similar to this:job.batch/process-item-apple created job.batch/process-item-banana created job.batch/process-item-cherry created Now, check on the jobs:kubectl get jobs -l jobgroup=jobexample The output is similar to this:NAME COMPLETIONS DURATION AGE process-item-apple 1/1 14s 22s process-item-banana 1/1 12s 21s process-item-cherry 1/1 12s 20s Using the -l option to kubectl selects only the Jobs that are part of this group of jobs (there might be other unrelated jobs in the system).You can check on the Pods as well using the same label selector:kubectl get pods -l jobgroup=jobexample The output is similar to:NAME READY STATUS RESTARTS AGE process-item-apple-kixwv 0/1 Completed 0 4m process-item-banana-wrsf7 0/1 Completed 0 4m process-item-cherry-dnfu9 0/1 Completed 0 4m We can use this single command to check on the output of all jobs at once:kubectl logs -f -l jobgroup=jobexample The output should be:Processing item apple Processing item banana Processing item cherry Clean up# Remove the Jobs you created # Your cluster automatically cleans up their Pods kubectl delete job -l jobgroup=jobexample Use advanced template parametersIn the first example, each instance of the template had one parameter, and that parameter was also used in the Job's name. However, names are restricted to contain only certain characters.This slightly more complex example uses the Jinja template language to generate manifests and then objects from those manifests, with a multiple parameters for each Job.For this part of the task, you are going to use a one-line Python script to convert the template to a set of manifests.First, copy and paste the following template of a Job object, into a file called job.yaml.jinja2:{% set params = [{ "name": "apple", "url": "http://dbpedia.org/resource/Apple", }, { "name": "banana", "url": "http://dbpedia.org/resource/Banana", }, { "name": "cherry", "url": "http://dbpedia.org/resource/Cherry" }] %} {% for p in params %} {% set name = p["name"] %} {% set url = p["url"] %} --- apiVersion: batch/v1 kind: Job metadata: name: jobexample-{{ name }} labels: jobgroup: jobexample spec: template: metadata: name: jobexample labels: jobgroup: jobexample spec: containers: - name: c image: busybox:1.28 command: ["sh", "-c", "echo Processing URL {{ url }} && sleep 5"] restartPolicy: Never {% endfor %} The above template defines two parameters for each Job object using a list of python dicts (lines 1-4). A for loop emits one Job manifest for each set of parameters (remaining lines).This example relies on a feature of YAML. One YAML file can contain multiple documents (Kubernetes manifests, in this case), separated by --- on a line by itself. You can pipe the output directly to kubectl to create the Jobs.Next, use this one-line Python program to expand the template:alias render_template='python -c "from jinja2 import Template; import sys; print(Template(sys.stdin.read()).render());"' Use render_template to convert the parameters and template into a single YAML file containing Kubernetes manifests:# This requires the alias you defined earlier cat job.yaml.jinja2 | render_template > jobs.yaml You can view jobs.yaml to verify that the render_template script worked correctly.Once you are happy that render_template is working how you intend, you can pipe its output into kubectl:cat job.yaml.jinja2 | render_template | kubectl apply -f - Kubernetes accepts and runs the Jobs you created.Clean up# Remove the Jobs you created # Your cluster automatically cleans up their Pods kubectl delete job -l jobgroup=jobexample Using Jobs in real workloadsIn a real use case, each Job performs some substantial computation, such as rendering a frame of a movie, or processing a range of rows in a database. If you were rendering a movie you would set $ITEM to the frame number. If you were processing rows from a database table, you would set $ITEM to represent the range of database rows to process.In the task, you ran a command to collect the output from Pods by fetching their logs. In a real use case, each Pod for a Job writes its output to durable storage before completing. You can use a PersistentVolume for each Job, or an external storage service. For example, if you are rendering frames for a movie, use HTTP to PUT the rendered frame data to a URL, using a different URL for each frame.Labels on Jobs and PodsAfter you create a Job, Kubernetes automatically adds additional labels that distinguish one Job's pods from another Job's pods.In this example, each Job and its Pod template have a label: jobgroup=jobexample.Kubernetes itself pays no attention to labels named jobgroup. Setting a label for all the Jobs you create from a template makes it convenient to operate on all those Jobs at once. In the first example you used a template to create several Jobs. The template ensures that each Pod also gets the same label, so you can check on all Pods for these templated Jobs with a single command.Note:The label key jobgroup is not special or reserved. You can pick your own labelling scheme. There are recommended labels that you can use if you wish.AlternativesIf you plan to create a large number of Job objects, you may find that:Even using labels, managing so many Jobs is cumbersome.If you create many Jobs in a batch, you might place high load on the Kubernetes control plane. Alternatively, the Kubernetes API server could rate limit you, temporarily rejecting your requests with a 429 status.You are limited by a resource quota on Jobs: the API server permanently rejects some of your requests when you create a great deal of work in one batch.There are other job patterns that you can use to process large amounts of work without creating very many Job objects.You could also consider writing your own controller to manage Job objects automatically.

Parallel Processing using Expansions


Configure Multiple SchedulersKubernetes ships with a default scheduler that is described here. If the default scheduler does not suit your needs you can implement your own scheduler. Moreover, you can even run multiple schedulers simultaneously alongside the default scheduler and instruct Kubernetes what scheduler to use for each of your pods. Let's learn how to run multiple schedulers in Kubernetes with an example.A detailed description of how to implement a scheduler is outside the scope of this document. Please refer to the kube-scheduler implementation in pkg/scheduler in the Kubernetes source directory for a canonical example.Before you beginYou need to have a Kubernetes cluster, and the kubectl command-line tool must be configured to communicate with your cluster. It is recommended to run this tutorial on a cluster with at least two nodes that are not acting as control plane hosts. If you do not already have a cluster, you can create one by using minikube or you can use one of these Kubernetes playgrounds:iximiuz LabsKillercodaKodeKloudPlay with KubernetesTo check the version, enter kubectl version.Package the schedulerPackage your scheduler binary into a container image. For the purposes of this example, you can use the default scheduler (kube-scheduler) as your second scheduler. Clone the Kubernetes source code from GitHub and build the source.git clone https://github.com/kubernetes/kubernetes.git cd kubernetes make Create a container image containing the kube-scheduler binary. Here is the Dockerfile to build the image:FROM busybox ADD ./_output/local/bin/linux/amd64/kube-scheduler /usr/local/bin/kube-scheduler Save the file as Dockerfile, build the image and push it to a registry. This example pushes the image to Google Container Registry (GCR). For more details, please read the GCR documentation. Alternatively you can also use the docker hub. For more details refer to the docker hub documentation.docker build -t gcr.io/my-gcp-project/my-kube-scheduler:1.0 . # The image name and the repository gcloud docker -- push gcr.io/my-gcp-project/my-kube-scheduler:1.0 # used in here is just an example Define a Kubernetes Deployment for the schedulerNow that you have your scheduler in a container image, create a pod configuration for it and run it in your Kubernetes cluster. But instead of creating a pod directly in the cluster, you can use a Deployment for this example. A Deployment manages a Replica Set which in turn manages the pods, thereby making the scheduler resilient to failures. Here is the deployment config. Save it as my-scheduler.yaml:admin/sched/my-scheduler.yaml apiVersion: v1 kind: ServiceAccount metadata: name: my-scheduler namespace: kube-system --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: my-scheduler-as-kube-scheduler subjects: - kind: ServiceAccount name: my-scheduler namespace: kube-system roleRef: kind: ClusterRole name: system:kube-scheduler apiGroup: rbac.authorization.k8s.io --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: my-scheduler-as-volume-scheduler subjects: - kind: ServiceAccount name: my-scheduler namespace: kube-system roleRef: kind: ClusterRole name: system:volume-scheduler apiGroup: rbac.authorization.k8s.io --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: my-scheduler-extension-apiserver-authentication-reader namespace: kube-system roleRef: kind: Role name: extension-apiserver-authentication-reader apiGroup: rbac.authorization.k8s.io subjects: - kind: ServiceAccount name: my-scheduler namespace: kube-system --- apiVersion: v1 kind: ConfigMap metadata: name: my-scheduler-config namespace: kube-system data: my-scheduler-config.yaml: | apiVersion: kubescheduler.config.k8s.io/v1 kind: KubeSchedulerConfiguration profiles: - schedulerName: my-scheduler leaderElection: leaderElect: false --- apiVersion: apps/v1 kind: Deployment metadata: labels: component: scheduler tier: control-plane name: my-scheduler namespace: kube-system spec: selector: matchLabels: component: scheduler tier: control-plane replicas: 1 template: metadata: labels: component: scheduler tier: control-plane version: second spec: serviceAccountName: my-scheduler containers: - command: - /usr/local/bin/kube-scheduler - --config=/etc/kubernetes/my-scheduler/my-scheduler-config.yaml image: gcr.io/my-gcp-project/my-kube-scheduler:1.0 livenessProbe: httpGet: path: /healthz port: 10259 scheme: HTTPS initialDelaySeconds: 15 name: kube-second-scheduler readinessProbe: httpGet: path: /healthz port: 10259 scheme: HTTPS resources: requests: cpu: '0.1' securityContext: privileged: false volumeMounts: - name: config-volume mountPath: /etc/kubernetes/my-scheduler hostNetwork: false hostPID: false volumes: - name: config-volume configMap: name: my-scheduler-config In the above manifest, you use a KubeSchedulerConfiguration to customize the behavior of your scheduler implementation. This configuration has been passed to the kube-scheduler during initialization with the --config option. The my-scheduler-config ConfigMap stores the configuration file. The Pod of themy-scheduler Deployment mounts the my-scheduler-config ConfigMap as a volume.In the aforementioned Scheduler Configuration, your scheduler implementation is represented via a KubeSchedulerProfile.Note:To determine if a scheduler is responsible for scheduling a specific Pod, the spec.schedulerName field in a PodTemplate or Pod manifest must match the schedulerName field of the KubeSchedulerProfile. All schedulers running in the cluster must have unique names.Also, note that you create a dedicated service account my-scheduler and bind the ClusterRole system:kube-scheduler to it so that it can acquire the same privileges as kube-scheduler.Please see the kube-scheduler documentation for detailed description of other command line arguments and Scheduler Configuration reference for detailed description of other customizable kube-scheduler configurations.Run the second scheduler in the clusterIn order to run your scheduler in a Kubernetes cluster, create the deployment specified in the config above in a Kubernetes cluster:kubectl create -f my-scheduler.yaml Verify that the scheduler pod is running:kubectl get pods --namespace=kube-system NAME READY STATUS RESTARTS AGE .... my-scheduler-lnf4s-4744f 1/1 Running 0 2m ... You should see a "Running" my-scheduler pod, in addition to the default kube-scheduler pod in this list.Enable leader electionTo run multiple-scheduler with leader election enabled, you must do the following:Update the following fields for the KubeSchedulerConfiguration in the my-scheduler-config ConfigMap in your YAML file:leaderElection.leaderElect to trueleaderElection.resourceNamespace to <lock-object-namespace>leaderElection.resourceName to <lock-object-name>Note:The control plane creates the lock objects for you, but the namespace must already exist. You can use the kube-system namespace.If RBAC is enabled on your cluster, you must update the system:kube-scheduler cluster role. Add your scheduler name to the resourceNames of the rule applied for endpoints and leases resources, as in the following example:kubectl edit clusterrole system:kube-scheduler admin/sched/clusterrole.yaml apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: annotations: rbac.authorization.kubernetes.io/autoupdate: "true" labels: kubernetes.io/bootstrapping: rbac-defaults name: system:kube-scheduler rules: - apiGroups: - coordination.k8s.io resources: - leases verbs: - create - apiGroups: - coordination.k8s.io resourceNames: - kube-scheduler - my-scheduler resources: - leases verbs: - get - update - apiGroups: - "" resourceNames: - kube-scheduler - my-scheduler resources: - endpoints verbs: - delete - get - patch - update Specify schedulers for podsNow that your second scheduler is running, create some pods, and direct them to be scheduled by either the default scheduler or the one you deployed. In order to schedule a given pod using a specific scheduler, specify the name of the scheduler in that pod spec. Let's look at three examples.Pod spec without any scheduler nameadmin/sched/pod1.yaml apiVersion: v1 kind: Pod metadata: name: no-annotation labels: name: multischeduler-example spec: containers: - name: pod-with-no-annotation-container image: registry.k8s.io/pause:3.8When no scheduler name is supplied, the pod is automatically scheduled using the default-scheduler.Save this file as pod1.yaml and submit it to the Kubernetes cluster.kubectl create -f pod1.yaml Pod spec with default-scheduleradmin/sched/pod2.yaml apiVersion: v1 kind: Pod metadata: name: annotation-default-scheduler labels: name: multischeduler-example spec: schedulerName: default-scheduler containers: - name: pod-with-default-annotation-container image: registry.k8s.io/pause:3.8 A scheduler is specified by supplying the scheduler name as a value to spec.schedulerName. In this case, we supply the name of the default scheduler which is default-scheduler.Save this file as pod2.yaml and submit it to the Kubernetes cluster.kubectl create -f pod2.yaml Pod spec with my-scheduleradmin/sched/pod3.yaml apiVersion: v1 kind: Pod metadata: name: annotation-second-scheduler labels: name: multischeduler-example spec: schedulerName: my-scheduler containers: - name: pod-with-second-annotation-container image: registry.k8s.io/pause:3.8 In this case, we specify that this pod should be scheduled using the scheduler that we deployed - my-scheduler. Note that the value of spec.schedulerName should match the name supplied for the scheduler in the schedulerName field of the mapping KubeSchedulerProfile.Save this file as pod3.yaml and submit it to the Kubernetes cluster.kubectl create -f pod3.yaml Verify that all three pods are running.kubectl get pods Verifying that the pods were scheduled using the desired schedulersIn order to make it easier to work through these examples, we did not verify that the pods were actually scheduled using the desired schedulers. We can verify that by changing the order of pod and deployment config submissions above. If we submit all the pod configs to a Kubernetes cluster before submitting the scheduler deployment config, we see that the pod annotation-second-scheduler remains in "Pending" state forever while the other two pods get scheduled. Once we submit the scheduler deployment config and our new scheduler starts running, the annotation-second-scheduler pod gets scheduled as well.Alternatively, you can look at the "Scheduled" entries in the event logs to verify that the pods were scheduled by the desired schedulers.kubectl get events You can also use a custom scheduler configuration or a custom container image for the cluster's main scheduler by modifying its static pod manifest on the relevant control plane nodes.

Configure Multiple Schedulers