How to Create Volume Snapshots and Restore Volumes from Snapshots in Kubernetes Clusters

DigitalOcean Kubernetes (DOKS) is a managed Kubernetes service that lets you deploy Kubernetes clusters without the complexities of handling the control plane and containerized infrastructure. Clusters are compatible with standard Kubernetes toolchains and integrate natively with DigitalOcean Load Balancers and block storage volumes.

You must have an existing volume in use in your cluster, which you can create by creating a PersistentVolumeClaim (PVC). For the purposes of this tutorial, presume we have already created a PVC by calling kubectl create -f your_pvc_file.yaml with a YAML file that looks like this:

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: csi-do-test-pvc
spec:
  accessModes:
  - ReadWriteOnce
  resources:
    requests:
      storage: 5Gi
  storageClassName: do-block-storage

Create a Snapshot of a Volume

To create a snapshot of a volume, call kubectl create -f your_snapshot_file.yaml and specify the desired PVC. Here's an example of a YAML file that defines a snapshot:

apiVersion: snapshot.storage.k8s.io/v1alpha1
kind: VolumeSnapshot
metadata:
  name: csi-do-test-snapshot
spec:
  source:
    name: csi-do-test-pvc
    kind: PersistentVolumeClaim

You can now observe the state of your volumes and snapshots in the DigitalOcean Control Panel or by using the following command:

$ kubectl get pvc && kubectl get pv && kubectl get volumesnapshot

Restore A Volume from a Snapshot

To restore from a given snapshot, you need to create a new PVC that refers to the snapshot by calling kubectl create -f your_restore_file.yaml. Here's an example of a YAML file that restores from a snapshot and creates a new PVC for use in the cluster:

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: csi-do-test-pvc-restore
spec:
  dataSource:
    name: csi-do-test-snapshot
    kind: VolumeSnapshot
    apiGroup: snapshot.storage.k8s.io
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 5Gi

More Information

For more details and examples of snapshot use in Kubernetes, see the official Kubernetes blog announcement.