Backing Up Workloads
local graph
Chapter 14 — Backing Up Workloads
Section titled “Chapter 14 — Backing Up Workloads”Backup products for Kubernetes are vital components of our ever-evolving journey into the world of container orchestration and cloud-native computing. In this chapter, we will explore using Velero’s capabilities and how it can help you ensure resilience and reliability for your workloads. Velero, meaning “safety” or “protection” in Italian, is a great name since it provides a safety net for your applications, allowing you to confidently run them in a dynamic, ever-changing environment.
As you dive deeper into Kubernetes and microservices, you will quickly realize the advantages of backing up, restoring, and migrating applications. While Kubernetes is a remarkable system for deploying and managing containerized applications, it doesn’t inherently provide tools for data protection and disaster recovery. This gap is filled by Velero, which presents a complete solution for safeguarding your Kubernetes workloads and the data connected with them.
Velero was originally known as Heptio Ark. Heptio was a company co-founded by two of Kubernetes’ original creators, Joe Beda and Craig McLuckie. Since then, it has become part of the VMware Tanzu portfolio, demonstrating its importance to the Kubernetes ecosystem.
In this chapter, we will explore the key features and use cases of Kubernetes and Velero, from basic backup and restore operations to more advanced scenarios like cross-cluster migrations. Whether you are just beginning your Kubernetes journey or are a seasoned Kubernetes operator, Velero is a tool worth learning.
In this chapter, we will cover the following topics:
- Understanding Kubernetes backups
- Performing an
etcdbackup - Introducing and setting up VMware’s Velero
- Using Velero to back up workloads and PVCs
- Managing Velero using the CLI
- Restoring from a backup
Technical requirements
Section titled “Technical requirements”To carry out the hands-on experiments in this chapter, you will need the following:
- An Ubuntu 22.04+ server running Docker with a minimum of 8 GB of RAM.
- A KinD cluster built to the specifications in Chapter 2.
- Scripts from the
chapter14folder from the repo, which you can access by going to this book’s GitHub repository: https://github.com/PacktPublishing/Kubernetes-An-Enterprise-Guide-Third-Edition
Understanding Kubernetes backups
Section titled “Understanding Kubernetes backups”Backing up a Kubernetes cluster requires backing up not only the workloads running on the cluster. You need to consider any persistent data and the cluster itself. Remember that the cluster state is maintained in an etcd database, making it a very important component that you need to back up in order to recover from any disasters.
Creating a backup of the cluster and the running workloads allows you to do the following:
- Migrate clusters.
- Create a development cluster from a production cluster.
- Recover a cluster from a disaster.
- Recover data from persistent volumes.
- Namespace and deployment recovery.
In this chapter, we will provide the details and tools to back up your etcd database, your namespace, the objects in them, and any persistent data you have attached to your workloads.
Recovering a cluster from a complete disaster in an enterprise usually involves backing up custom SSL certificates for various components, such as Ingress controllers, load balancers, and the API server. Since the process of backing up all custom components is different in many environments, we will focus on the procedures that are common among most Kubernetes distributions.
As you know, the cluster state is maintained in etcd, and if you lose all of your etcd instances, you will lose your cluster. In a multi-node control plane, you should have a minimum of three etcd instances, providing redundancy for the cluster. If you lose a single node, the cluster will remain running, and you can replace the failed node with a new node. Once the new instance has been added, it will receive a copy of the etcd database and your cluster will be back to full redundancy.
In the event that you lose all of your etcd servers without any backup of the database, you would lose the cluster, including the cluster state and all of the workloads. Since etcd is so important, the etcdctl utility includes a built-in backup function. In the next section, we will show you how to take an etcd backup using the etcdctl utility.
Performing an etcd backup
Section titled “Performing an etcd backup”Since we are using KinD for our Kubernetes cluster, we can create a backup of the etcd database, but we will not be able to restore it.
Our etcd server is running in a pod on the cluster called etcd-cluster01-control-plane, located in the kube-system namespace. During the creation of the KinD cluster, we added an extra port mapping for the control plane node, exposing port 2379, which is used to access etcd. In your own production environment, you may not have the etcd port exposed for external requests, but the process of backing up the database will still be similar to the steps explained in this section.
Backing up the required certificates
Section titled “Backing up the required certificates”Most Kubernetes installations store certificates in /etc/kubernetes/pki. In this respect, KinD is no different, so we can back up our certificates using the docker cp command.
We have said it a few times: etcd is very important! So, it stands to reason that accessing the database directly probably has some security around it. Well, it does, and to access it, you need to provide the correct certificates when you execute a command against the database. In an enterprise, you should store these keys in a secure location. For our example, we will pull the certificates from the KinD nodes.
We have included a script in the chapter14/etcd directory called install-etcd-tools.sh that will execute the steps to download and execute the backup of the etcd database. To execute the script, change to the chapter14/etcd directory and execute the installation script.
Running the script will download the etcd tools, extract them, and move them to usr/bin so we can execute them easily. It will then create a directory for the certificates and copy them into the newly created directory, /etcd/certs. The certificates that we will use for backing up etcd are:
ca.crthealthcheck-client.crthealthcheck-client.key
When you execute commands using the etcdctl utility, you will need to provide the keys or your actions will be denied.
Now that we have the certificates required to access etcd, the next step is to create a backup of the database.
Backing up the etcd database
Section titled “Backing up the etcd database”The creators of etcd created a utility that backs up and restores the etcd database, called etcdctl. For our purposes, we will only use the backup operation; however, since etcd is not exclusive to Kubernetes, the utility has a number of options that you will not use as a Kubernetes operator or developer. If you want to read more about this utility, you can visit the etcd-io Git repository at https://github.com/etcd-io/etcd.
To back up a database, you will need the etcdctl utility and the certificates required to access the database, which we copied from the control plane server.
The script that we executed in the last section downloaded etcctl, and we moved it into usr/bin. To create a backup of the database, make sure you are in the chapter14/etcd directory and that the certs directory exists with the downloaded certificates.
To back up etcd, we execute the etcd snapshot save command:
etcdctl snapshot save etcd-snapshot.db --endpoints=https://127.0.0.1:2379 --cacert=./certs/ca.crt --cert=./certs/healthcheck-client.crt --key=./certs/healthcheck-client.keyOlder versions of etcdctl required you to set the API version to 3 using ETCDCTL_API=3 since they default to the version 2 API. etcd 3.4 changed the default API to 3, so we do not need to set that variable before using etcdctl commands.
It shouldn’t take too long for the database to be copied over. If it takes more than a few seconds, you should try the same command with the --debug=true flag. Adding the debug flag will provide more output during the execution of the snapshot. The most common reason for the snapshot failing is an incorrect certificate. Below is an example of the verbose output from a snapshot command that had an incorrect certificate:
2023/11/17 21:39:19 INFO: [core] Creating new client transport to "{Addr: \"127.0.0.1:2379\", ServerName: \"127.0.0.1:2379\", }": connection error: desc = "transport: authentication handshake failed: tls: failed to verify certificate: x509: certificate signed by unknown authority (possibly because of \"crypto/rsa: verification error\" while trying to verify candidate authority certificate \"etcd-ca\")"Notice the x509 error. This is likely caused by an incorrect certificate in your etcdctl command. Check that you have the correct certificates, and re-run the command.
If the command is successful, you will receive output similar to this:
{"level":"info","ts":"2023-11-17T21:44:38.316265Z","caller":"snapshot/v3_snapshot.go:65","msg":"created temporary db file","path":"etcd-snapshot.db.part"}{"level":"info","ts":"2023-11-17T21:44:38.329699Z","logger":"client","caller":"[email protected]/maintenance.go:212","msg":"opened snapshot stream; downloading"}{"level":"info","ts":"2023-11-17T21:44:38.329756Z","caller":"snapshot/v3_snapshot.go:73","msg":"fetching snapshot","endpoint":"https://127.0.0.1:2379"}{"level":"info","ts":"2023-11-17T21:44:38.45673Z","logger":"client","caller":"[email protected]/maintenance.go:220","msg":"completed snapshot read; closing"}{"level":"info","ts":"2023-11-17T21:44:38.461743Z","caller":"snapshot/v3_snapshot.go:88","msg":"fetched snapshot","endpoint":"https://127.0.0.1:2379","size":"6.6 MB","took":"now"}{"level":"info","ts":"2023-11-17T21:44:38.46276Z","caller":"snapshot/v3_snapshot.go:97","msg":"saved","path":"etcd-snapshot.db"}Snapshot saved at etcd-snapshot.dbNext, we can verify that the database was copied over successfully by trying a simple etcdctl command that will provide a summary of the backup:
etcdctl --write-out=table snapshot status etcd-snapshot.dbThis will output an overview of the backup:
+----------+----------+------------+------------+| HASH | REVISION | TOTAL KEYS | TOTAL SIZE |+----------+----------+------------+------------+| 224e9348 | 6222 | 1560 | 6.6 MB |+----------+----------+------------+------------+For this example, we only backed up the etcd database once. In a real-life scenario, you should create a scheduled process that executes a snapshot of etcd at regular intervals and stores the backup file in a safe, secure location.
Due to how KinD runs the control plane, we cannot use the restore procedures in this section. We are providing only the backup steps in this section so that you know how to back up an etcd database in an enterprise environment.
So far, you have learned about the critical importance of backing up both workloads and persistent data in Kubernetes, including the etcd database. Having a good backup strategy allows you to facilitate cluster migrations, create new development clusters from production clusters, and recover from disasters. By knowing these strategies, you can ensure improved disaster recovery preparedness, enhanced operational efficiency, and data security. Mastering these techniques will equip you to manage and recover Kubernetes clusters more effectively, ensuring a resilient and reliable environment.
Now, let’s move on and introduce the tool we will use to demonstrate Kubernetes backups: Velero.
Introducing and setting up VMware’s Velero
Section titled “Introducing and setting up VMware’s Velero”Velero is an open-source backup solution for Kubernetes that was originally developed by a company called Heptio. As VMware has enhanced its support for Kubernetes, it has purchased multiple companies, and Heptio is one of its acquisitions, bringing Velero into the VMware portfolio.
VMware has moved most of its offerings around Kubernetes under the Tanzu umbrella. This can be a little confusing for some people since the original iteration of Tanzu was a deployment of multiple components that added Kubernetes support to vSphere clusters. Since the initial incarnation of Tanzu, it has come to include components such as Velero, Harbor, and the Tanzu Application Platform (TAP), none of which require vSphere to function; they will run natively in any standard Kubernetes cluster.
Even with all of the ownership and branding changes, the base functions of Velero have remained. It offers many features that are only available in commercial products, including scheduling, backup hooks, and granular backup controls – all for no charge.
While Velero is free, it has a learning curve since it does not include an easy-to-use GUI like most commercial products. All operations in Velero are carried out using their command-line utility, an executable called velero. This single executable allows you to install the Velero server, create backups, check the status of backups, restore backups, and more. Since every operation for management can be done with one file, restoring a cluster’s workloads is a very easy process. In this chapter, we will create a second KinD cluster and populate it with a backup from an existing cluster.
But before that, we need to take care of a few requirements.
Velero requirements
Section titled “Velero requirements”Velero consists of a few components with which you create a backup system:
- The Velero CLI: This provides the installation of Velero components. It is used for all backup and restore functions.
- The Velero server: This is responsible for executing backup and restore procedures.
- Storage provider plug-ins: These are used for backing up and restoring to specific storage systems.
Outside of the base Velero components, you will also need to provide an object storage location that will be used to store your backups. If you do not have an object storage solution, you can deploy MinIO, which is an open-source project that provides an S3-compatible object store. We will deploy MinIO in our KinD cluster to demonstrate the backup and restore features provided by Velero.
Installing the Velero CLI
Section titled “Installing the Velero CLI”The first step of deploying Velero is to download the latest Velero CLI binary. We have included a script to install the Velero binary in the chapter14 directory called install-velero-binary.sh, which will download the Velero binary, move it to /usr/bin, and then output the version of Velero to verify that the binary has been installed correctly. As of the writing of this chapter, the latest version of Velero is 1.12.1.
You can safely ignore the last line, which shows an error in finding the Velero server. Right now, all we have installed is the Velero executable, and it can’t find the server yet. In the next section, we will install the server to complete the installation.
Installing Velero
Section titled “Installing Velero”Velero has minimal system requirements, most of which are easily met:
- A Kubernetes cluster running version 1.16 or higher
- The Velero executable
- Images for the system components
- A compatible storage location
- A volume snapshot plugin (optional)
Depending on your infrastructure, you may not have a compatible location for the backups or snapshotting volumes. Fortunately, if you do not have a compatible storage system, there are open-source options that you can add to your cluster to meet the requirements.
In the next section, we will explain the natively supported storage options and since our example will use a KinD cluster, we will install open-source options to add compatible storage to use as a backup location.
Backup storage location
Section titled “Backup storage location”Velero requires an S3-compatible bucket to store backups. There are a number of officially supported systems, including all object store offerings from AWS, Azure, and Google.
In the following table, the Support column means that the plugin provides a compatible location for storing Velero backups. The Volume Snapshot Support column means that the plugin supports backing up persistent volumes using snapshots. If the CSI in use does not provide snapshot support, data will be backed up using a standard file system backup via Restic or Kopia. Snapshots offer several advantages, with the most significant being their ability to maintain application consistency. Velero ensures that snapshots are captured in a manner that maintains the state of the application, minimizing the likelihood of data corruption.
Along with the officially supported providers, there are a number of community- and vendor-supported providers from companies such as DigitalOcean, Hewlett-Packard, and Portworx. The following table lists all of the current providers:
| Vendor | Object Store | Volume Snapshot Support | Support |
|---|---|---|---|
| Amazon | AWS S3 | AWS EBS | Official |
| Google Cloud Storage | GCE Disks | Official | |
| Microsoft | Azure Blob Storage | Azure Managed Disks | Official |
| VMware | Not Supported | vSphere Volumes | Official |
| Kubernetes CSI | Not Supported | CSI Volumes | Official |
| Alibaba Cloud | Alibaba Cloud OSS | Alibaba Cloud | Community |
| DigitalOcean | DigitalOcean Object Storage | DigitalOcean Volumes Block Storage | Community |
| HP | Not Supported | HPE Storage | Community |
| OpenEBS | Not Supported | OpenEBS cStor Volumes | Community |
| Portworx | Not Supported | Portworx Volumes | Community |
| Storj | Storj Object Storage | Not Supported | Community |
Table 14.1: Velero storage options
If you do not have an object storage solution, you can deploy the open-source S3 provider MinIO, which is what we will use for our S3 target in this chapter.
Now that the Velero executable has been installed and our KinD cluster has persistent storage, thanks to the auto-provisioner from Rancher, we can move on to the first requirement – adding an S3-compatible backup location for Velero.
Deploying MinIO
Section titled “Deploying MinIO”MinIO is an open-source object storage solution that is compatible with Amazon’s S3 cloud services API. You can read more about MinIO in its GitHub repository at https://github.com/minio/minio.
If you install MinIO using a manifest from the internet, be sure to verify what volumes are declared in the deployment before trying to use it as a backup location. Many of the examples on the internet use emptyDir: {}, which is not persistent.
We have included a modified MinIO deployment from the Velero GitHub repository in the chapter14 folder. Since we have persistent storage on our cluster, we edited the volumes in the deployment to use Persistent Volume Claims (PVCs), which will use the auto-provisioner for Velero’s data and configuration.
To deploy the MinIO server, change directories to chapter14 and execute kubectl create. The deployment will create a Velero namespace, PVCs, and MinIO on your KinD cluster. It may take some time for the deployment to complete. We have seen the deployment take anything from a minute to a few minutes, depending on the host system:
kubectl create -f minio-deployment.yamlThis will deploy the MinIO server and expose it as minio on port 9000/TCP, with the console on port 9001/TCP, as follows:
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGEconsole ClusterIP 10.102.216.91 <none> 9001/TCP 42hminio ClusterIP 10.110.216.37 <none> 9000/TCP 42hThe MinIO server can be targeted by any pod in the cluster, with correct access keys, using minio.velero.svc on port 9000.
With MinIO deployed, we need to expose the console using an Ingress rule so we can log in to look at buckets and verify that backups are working as expected.
Exposing MinIO and the console
Section titled “Exposing MinIO and the console”By default, your MinIO storage will only be available inside the cluster it has been deployed in. Since we will demonstrate restoring to a different cluster at the end of the chapter, we need to expose MinIO using an Ingress rule. MinIO also includes a dashboard that allows you to browse the contents of the S3 buckets on the server. To allow access to the dashboard, you can deploy an Ingress rule that exposes the MinIO console.
We have included a script in the chapter14 folder called create-minio-ingress.sh that will create an Ingress rule using the nip.io syntax of minio-console.w.x.y.z.nip.ip and minio.w.x.y.z.nip.ip, with your host IP.
You will need the console Ingress rule when you install Velero in your cluster.
Once deployed, you can use a browser on any machine and open the URL you used for the Ingress rule. On our cluster, the host IP is 10.2.1.161, so our URL is minio-console.10.2.1.161.nip.io:

Figure 14.1: MinIO dashboard
To access the dashboard, supply the access key and secret key from the MinIO deployment. If you used the MinIO installer from the GitHub repository, the username and password have been defined in the manifest. They are packt/packt123.
Once logged in, you will see a list of buckets and any items that are stored in them. You should see a bucket named velero, which is the bucket we will use to back up our cluster. This bucket was created during the initial MinIO deployment – we added a line to the deployment that creates the velero bucket and the required permissions for the packt user.

Figure 14.2: MinIO browser
If you are new to object storage, it is important to note that while this deploys a storage solution in your cluster, it will not create a StorageClass or integrate with Kubernetes in any way. All pod access to the S3 bucket is done using the URL that we will provide in the next section.
Now that you have an S3-compatible object store running, you need to create a configuration file that Velero will use to target your MinIO server.
Installing Velero
Section titled “Installing Velero”To deploy Velero in your cluster, you can use the Velero binary or a Helm chart. We have chosen to install Velero using the binary.
Before we start the installation, we need to create a credentials file that will contain the access_key and secret_access_key for the S3 target on MinIO.
Create a new credential file in the chapter14 folder called credentials-velero with the following content:
[default]aws_access_key_id = packtaws_secret_access_key = packt123Next, we can deploy Velero using the Velero executable and the install option to deploy Velero with the option to back up persistent volumes.
Execute the Velero installation using the following command from inside the chapter14 folder to deploy Velero. Please note that you need to provide your nip.io ingress name for MinIO. We exposed both MinIO and the console when we created the Ingress rule earlier. Be careful to use the ingress name that contains minio.w.x.y.z.nip.io; do not use the minio-console ingress or Velero will fail to find the S3 bucket.
velero install --provider aws --plugins velero/velero-plugin-for-aws:v1.2.0 --bucket velero --secret-file ./credentials-velero --use-volume-snapshots=false --backup-location-config region=minio,s3ForcePathStyle="true",s3Url=http://minio.velero.svc:9000 --use-node-agent --default-volumes-to-fs-backupLet’s explain the installation options and what the values mean:
| Option | Description |
|---|---|
--provider | Configures Velero to use a storage provider. Since we are using MinIO, which is S3-compatible, we are passing aws as our provider. |
--plugins | Tells Velero the backup plugin to use. For our cluster, since we are using MinIO for object storage, we selected the AWS plugin. |
--bucket | The name of the S3 bucket that you want to target. |
--secret-file | Points to the file that contains the credentials to authenticate with the S3 bucket. |
--use-volume-snapshots | Will enable or disable volume snapshots for providers that support snapshots. Currently, Velero only supports object storage with snapshots; if snapshots are not supported, this should be set to false. Since we are not interested in snapshots for our examples, we set this to false. |
--backup-location-config | The S3 target location where Velero will store backups. Since MinIO is running in the same cluster as Velero, we can target S3 using the name minio.velero.svc:9000. In a production environment, you would use MinIO in the same cluster – you will likely have an external S3 target to store your backups. Using the Kubernetes service name will cause Velero describe commands to have some errors since it tries to query the cluster using the name provided, and you cannot access minio.velero.svc from outside of the cluster. |
--use-node-agent | Add this flag if you want to back up persistent volumes using Velero’s node agent. |
--default-volumes-to-fs-backup | Configures Velero to support opting out of backing up persistent volumes. If this isn’t added during deployment, you can still use the option during a Velero backup to back up volumes. This will be explained more in the Backing up PVCs section of this chapter. |
Table 14.2: Velero install options
When you execute the install, you will see a number of objects being created, including a number of CustomResourceDefinitions (CRDs) and other objects that Velero uses to handle backup and restore operations.
If you run into issues with your Velero server starting up correctly, there are a few CRDs and Secrets that you can look at that may have incorrect information. In the following table, we explain some of the common objects that you may need to interact with when using Velero:
CustomResourceDefinition | Name | Description |
|
| Each backup that is created will create an object called |
|
| Each backup storage location creates a |
|
| Each scheduled backup creates a |
|
| If enabled, the |
Secret Name | Description | |
| Contains the credentials to connect to the storage provider in Base64 format. If your Velero pod fails to start up, you may have an incorrect value in the | |
| If you are using the Restic plugin, this will contain your repository password, similar to | |
Table 14.3: Velero’s CRDs and Secrets
While most of your interaction with these objects will be through the Velero executable, it is always a good practice to understand how utilities interact with the API server. Understanding the objects and what their functions are is helpful if you do not have access to the Velero executable but you need to view, or potentially change, an object value to address an issue quickly.
Now that we have Velero installed and a high-level understanding of Velero objects, we can move on to creating different backup jobs for a cluster.
Using Velero to back up workloads and PVCs
Section titled “Using Velero to back up workloads and PVCs”Velero supports running a one-time backup with a single command or on a recurring schedule. Whether you choose to run a single backup or a recurring backup, you can back up all objects or only certain objects using include and exclude flags.
Backing up PVCs
Section titled “Backing up PVCs”Since data is becoming increasingly common on Kubernetes clusters, we will back up all of the cluster workloads, including any PVCs that are in the cluster. When we installed Velero, we added the --use-node-agent option, which created a DaemonSet that creates a node agent on each cluster node. The DaemonSet deploys a pod containing modules that can perform file system backups, including a data mover, which may be Restic or Kopia (default) on each node, and a new secret is created in the velero namespace called velero-repo-credentials. This secret contains a repository-password that will be used for your backups. This is a generated password, and you can change it to anything you want – however, if you plan to change the password, do it before creating any backups. If this password is changed after you have created any backups, Velero will not be able to read the old backups.
The default ServiceAccount token, Secrets, and ConfigMaps can be mapped to volumes. These are not volumes that contain data and will not be backed up using the node agent. Like any other base Kubernetes objects, they will be backed up when Velero backs up the other namespace objects.
The data movers are responsible for copying the data from the volumes. Previous Velero releases used Restic as the data mover, but it has been enhanced to include both Restic and Kopia in the node DaemonSet. By default, Kopia will be used as the data mover, but if you want to use Restic, you can change the default by adding the option --data-mover restic to your Velero backup create command. There is some debate around which data mover to use and Kopia has become the leader, so it has become the default.
Velero can be configured to back up PVCs via two different approaches:
- Opt-out: Velero will back up all PVCs, unless a workload is annotated with the volume name(s) to ignore.
- Opt-in: Only workloads that have an annotation with the volume’s name will be backed up. This is Velero’s default configuration.
Let’s take a closer look at these two approaches.
Using the opt-out approach
Section titled “Using the opt-out approach”This is the approach we will use for the exercises. When using this approach, all PVCs will be backed up unless you specify an annotation in the pod, adding backup.velero.io/backup-volumes-excludes. For example, if you had 3 PVCs named volume1, volume2, and volume3 in a namespace and you wanted to exclude volume2 and volume3 from being backed up, you would need to add the following annotation to the pod spec in your deployment:
backup.velero.io/backup-volumes-excludes=volume2,volume3Since we added only volume2 and volume3 to the exclusion, Velero will ignore those volumes from the backup, but it will back up the PVC named volume1 since it was not included in the list.
During the installation of Velero, we set --default-volumes-to-fs-backup, which tells Velero to back up all persistent data, unless a volume has an annotation to exclude it from being backed up. If you didn’t set that option during your Velero deployment, you can tell Velero to use the opt-out approach for a single backup by adding the same option, --default-volumes-to-fs-backup, to the backup command.
velero backup create BACKUP_NAME --default-volumes-to-fs-backup OTHER_OPTIONSWhen a backup is created using this option, Velero will back up every persistent volume that is attached to pods, unless it has been excluded in the excludes annotation.
Using the opt-in approach
Section titled “Using the opt-in approach”If you deployed Velero without the --default-volumes-to-fs-backup option, persistent volumes will not be backed up unless you add an annotation to tell Velero to back up the required volumes.
Similarly to how you opted out in the previous example, you can add an annotation to your deployment to instruct Velero to back up your volume or volumes. The annotation that you need to add is backup.velero.io/backup-volumes, and the following example tells Velero to back up two volumes, one called volume1 and the other called volume2:
kubectl -n demo annotate deploy/demo backup.velero.io/backup-volumes=volume1,volume2When you run your next backup, Velero will see the annotation and will add the two persistent volumes to the backup job.
Limitations of backing up data
Section titled “Limitations of backing up data”Velero cannot back up a volume that is using hostPath for the persistent data. The local-path-provisioner maps persistent disks to a hostPath by default, meaning that Velero will not be able to back up or restore the data. Luckily, there is an option to change the type from hostPath to local, which will work with Velero. When you create a new PVC, you can add an annotation of volumeType: local. The example below shows a PVC manifest that would be created as a local type, rather than hostPath:
kind: PersistentVolumeClaimapiVersion: v1metadata: name: test-claim namespace: demo annotations: volumeType: localspec: accessModes: - ReadWriteOnce resources: requests: storage: 1GiThis change is not needed in many cases, but since it’s required when using the local-path-provisioner, we will need to add the annotation to any PVCs that we want to test with Velero.
With Velero deployed with the ability to back up our persistent data, let’s jump into creating a one-time backup of our cluster.
Running a one-time cluster backup
Section titled “Running a one-time cluster backup”To create an initial backup, you can run a single Velero command that will back up all of the namespaces in the cluster and if there are any PVCs that have not been annotated to be ignored, they will also be backed up.
Executing a backup without any flags to include or exclude any cluster objects will back up every namespace and all of the objects in the namespace.
We will use what we learn in this section to perform a restore to show Velero in action. For our backup, we will back up the entire cluster, including the PVCs.
Before we start a backup, we are going to add a deployment with a PVC, where we will add a few empty files to verify that restoring data works as expected.
In the chapter14/pvc-example directory, there is a manifest called busybox-pvc.yaml. To deploy the example, you should execute the command from within the chapter14/pvc-example directory:
kubectl create -f busybox-pvc.yamlThe script will create a new namespace called demo with the busybox-pvc pod deployed using a PVC named test-claim, mounted in the /mnt directory of the container.
Right now, the PVC has one file, original-data, in it. We need to add a few other files to test a restore a little later. First, let’s verify the current contents of the PVC using kubectl exec to list the directory contents. If you are following along on your own cluster, you will need to change the busybox-pvc pod name to whatever is in use on your cluster. You can get the pod name using kubectl get pods -n demo:
kubectl get pods -n demoThis will list the busybox pod information. You will need the pod name to execute the exec command to create the files in the PVC:
NAME READY STATUS RESTARTS AGEbusybox-pvc-6cb895b675-grnxq 1/1 Running 0 4m29skubectl exec -it busybox-pvc-f7bfbcc44-vfsnf -n demo -- ls /mnt -latotal 8drwxrwxrwx 2 root root 4096 Dec 7 15:41 .drwxr-xr-x 1 root root 4096 Dec 7 15:41 ..-rw-r--r-- 1 root root 0 Dec 7 15:41 original-dataNow, let’s add two additional files called newdata1 and newdata2 to the pod. To do this, we will use another kubectl exec command that will touch files in the /mnt directory.
kubectl exec -it busybox-pvc-f7bfbcc44-vfsnf -n demo -- touch /mnt/newfile1kubectl exec -it busybox-pvc-f7bfbcc44-vfsnf -n demo -- touch /mnt/newfile2Again, to verify the data has been written successfully, we can list the contents using kubectl exec:
kubectl exec -it busybox-pvc-f7bfbcc44-vfsnf -n demo -- ls /mnt -la total 8drwxrwxrwx 2 root root 4096 Dec 7 15:48 .drwxr-xr-x 1 root root 4096 Dec 7 15:46 ..-rw-r--r-- 1 root root 0 Dec 7 15:48 newfile1-rw-r--r-- 1 root root 0 Dec 7 15:48 newfile2-rw-r--r-- 1 root root 0 Dec 7 15:41 original-dataGreat! We can see that the two new files have been created. Now that we have new data in the pod, we can move on to backing up our cluster.
To create a one-time backup, execute the velero command with the backup create <backup name> option. In our example, we have named the backup initial-backup:
velero backup create initial-backupThe only confirmation you will receive from this is that the backup request was submitted:
Backup request "initial-backup" submitted successfully.Run \`velero backup describe initial-backup\` or \`velero backup logs initial-backup\` for more details.Fortunately, Velero also tells you the command to check the backup status and logs. The last line of the output tells us that we can use the velero command with the backup option and either describe or logs to check the status of the backup operation.
The describe option will show all of the details of the job. An example is shown below:
velero backup describe initial-backupName: initial-backupNamespace: veleroLabels: velero.io/storage-location=defaultAnnotations: velero.io/resource-timeout=10m0s velero.io/source-cluster-k8s-gitversion=v1.28.0 velero.io/source-cluster-k8s-major-version=1 velero.io/source-cluster-k8s-minor-version=28Phase: CompletedNamespaces: Included: * Excluded: <none>Resources: Included: * Excluded: <none> Cluster-scoped: autoLabel selector: <none>Or label selector: <none>Storage Location: default
Velero-Native Snapshot PVs: autoSnapshot Move Data: falseData Mover: veleroTTL: 720h0m0sCSISnapshotTimeout: 10m0sItemOperationTimeout: 4h0m0sHooks: <none>Backup Format Version: 1.1.0Started: 2023-12-06 18:46:57 +0000 UTCCompleted: 2023-12-06 18:48:15 +0000 UTCExpiration: 2024-01-05 18:46:57 +0000 UTCTotal items to be backed up: 641Items backed up: 641Velero-Native Snapshots: <none included>kopia Backups (specify --details for more information): Completed: 4Notice the last section. This section tells us that Velero backed up 4 PVCs using the Kopia data mover. We will show this more when we perform a backup.
To reinforce the previous section, where we mentioned some of the CRDs that Velero uses, we also want to explain where the Velero utility retrieves this information from.
Each backup that is created will create a backup object in the Velero namespace. For our initial backup, a new backup object named initial-backup was created. Using kubectl, we can describe the object to see similar information that the Velero executable will provide.
As shown in the preceding output, the describe option shows you all of the settings for the backup job. Since we didn’t pass any options to the backup request, the job contains all the namespaces and objects. Some of the most important details to verify are the phase, the total items to be backed up, and the items backed up.
If the status of the phase is anything other than success, you may not have all the items that you want in your backup. It’s also a good idea to check the backed-up items; if the number of items backed up is less than the items to be backed up, our backup did not back up all of the items.
You may need to check the status of a backup, but you may not have the Velero executable installed. Since this information is in a CR, we can describe the CR to retrieve the backup details. Running kubectl describe on the backup object will show the status of the backup:
kubectl describe backups initial-backup -n veleroIf we jump to the bottom of the output from the describe command, you will see the following:
Name: initial-backupNamespace: veleroLabels: velero.io/storage-location=defaultAnnotations: velero.io/resource-timeout: 10m0s velero.io/source-cluster-k8s-gitversion: v1.28.0 velero.io/source-cluster-k8s-major-version: 1 velero.io/source-cluster-k8s-minor-version: 28API Version: velero.io/v1Kind: BackupMetadata: Creation Timestamp: 2023-12-06T18:46:57Z Generation: 15 Resource Version: 35606 UID: 005da7ae-f270-470e-8907-c122815af365Spec: Csi Snapshot Timeout: 10m0s Default Volumes To Fs Backup: true Hooks: Included Namespaces: * Item Operation Timeout: 4h0m0s Metadata: Snapshot Move Data: false Storage Location: default Ttl: 720h0m0s Volume Snapshot Locations: defaultStatus: Completion Timestamp: 2023-12-06T18:48:15Z Expiration: 2024-01-05T18:46:57Z Format Version: 1.1.0 Phase: Completed Progress: Items Backed Up: 641 Total Items: 641 Start Timestamp: 2023-12-06T18:46:57Z Version: 1 Warnings: 3Events: <none>In the output, you can see that the phase is completed, the start and completion times, and the number of objects that were backed up and included in the backup.
It’s good practice to use a cluster add-on that can generate alerts based on information in log files or the status of an object, such as AlertManager.
You always want a successful backup, and if a backup fails, you should look into the failure immediately.
To verify that the backup is correctly stored in our S3 target, go back to the MinIO console, and if you are not already in the Bucket view, click Buckets on the left-hand side. If you are already on the Bucket screen, press F5 to refresh your browser to update the view. Once the view has been refreshed, you should see that the velero bucket has objects stored in it. Clicking on the bucket will show you another screen, where you will see two folders, one for backup and one for Kopia. Velero will split the data from the Kubernetes objects by storing data in the kopia (or restic, if that was used as the data mover) folder. All Kubernetes objects will be stored in the backups folder.

Figure 14.3: Bucket details
Since the overview of the velero bucket shows storage usage and a number of objects, and we see the backups and kopia folders, we can safely assume that the initial backup was successful. We will use this backup to restore a deleted namespace in the Restoring from a backup section of this chapter.
A one-off backup is not something you will likely run often. You should back up your cluster on a regular, scheduled basis. In the next section, we will explain how to create a scheduled backup.
Scheduling a cluster backup
Section titled “Scheduling a cluster backup”Creating a one-time backup is useful if you have a cluster operation scheduled or if there is a major software upgrade in a namespace. Since these events will be rare, you will want to schedule backing up the cluster at regular intervals, rather than random one-time backups.
To create a scheduled backup, you use the schedule option and create a tag with the Velero executable. Along with the schedule and creating the tag, you need to provide a name for the job and the schedule flag, which accepts cron -based expressions. The following schedule tells Velero to back up at 1 A.M. every day:

Figure 13.7 – Cron scheduling expression
Figure 14.4: Cron scheduling expression
Using the information in Figure 14.4, we can create a backup that will run at 1 A.M., using the following velero schedule create command:
velero schedule create cluster-daily-1 --schedule="0 1 * * *"Velero will reply that a schedule has been successfully created:
Schedule "cluster-daily-1" created successfully.If you are not familiar with cron and the options that are available, you should read the cron package documentation at https://godoc.org/github.com/robfig/cron.
cron will also accept some shorthand expressions, which may be easier than using the standard cron expressions. The following table contains the shorthand for predefined schedules:
| Shorthand value | Description |
|---|---|
@yearly | Executes once a year at midnight on January 1 st |
@monthly | Executes once a month, on the first day of the month, at midnight |
@weekly | Executes once a week, on Sunday morning at midnight |
@daily | Executes daily at midnight |
@hourly | Executes at the beginning of each hour |
Table 14.4: cron shorthand scheduling
Using the values from the shorthand table to schedule a backup job that executes daily at midnight, we use the following Velero command:
velero schedule create cluster-daily-2 --schedule="@daily"This will create a backup job that backs the cluster up at midnight, each night. You can verify that the job was created and the last time it ran by looking at the schedules object, using kubectl get schedules -n velero:
NAMESPACE NAME STATUS SCHEDULE LASTBACKUP AGE PAUSEDvelero cluster-daily Enabled @daily 63sScheduled jobs will create a backup object when the job is executed. The backup name will contain the name of the schedule, with a dash and the date and time of the backup. Backup names follow the standard naming of YYYYMMDDhhmmss. Using the name from the preceding example, our initial backup was created with the name cluster-daily-20231206200028. Here, 20231206200028 is the date the backup ran, and 200028 is the time the backup ran in UTC time. This is the equivalent of 2021-09-30 20:00:28 +0000 UTC.
All of our examples so far have been configured to back up all of the namespaces and objects in the cluster. You may need to create different schedules or exclude/include certain objects based on your specific clusters.
In the next section, we will explain how to create a custom backup that will allow you to use specific tags to include and exclude namespaces and objects.
Creating a custom backup
Section titled “Creating a custom backup”When you create any backup job, you can provide flags to customize what objects will be included in or excluded from the backup job. Some of the most common flags are detailed here:
| Flag | Description |
|---|---|
--exclude-namespaces | Comma-separated list of namespaces to exclude from the backup job. Example: --exclude-namespaces web-dev1,web-dev2. |
--exclude-resources | Comma-separated list of resources to exclude, formatted as resource.group. Example: --exclude-resources storageclasses.storage.k8s.io. |
--include-namespaces | Comma-separated list of namespaces to include in the backup job. Example: --include-namespaces web-dev1,web-dev2. |
--selector | Configures the backup to include only objects that match a label selector. Accepts a single value only. Example: --selector app.kubernetes.io/name=ingress-nginx. |
--ttl | Configures how long to keep the backup in hours, minutes, and seconds. By default, the value is set for 30 days or 720h0m0s. Example: --ttl 24h0m0s. This will delete the backup after 24 hours. |
Table 14.5: Velero backup flags
To create a scheduled backup that will run daily and include only Kubernetes system namespaces, we would create a scheduled job using the --include-namespaces flag:
velero schedule create cluster-ns-daily --schedule="@daily" --include-namespaces ingress-nginx,kube-node-lease,kube-public,kube-system,local-path-storage,veleroSince Velero commands use a CLI for all operations, we should start by explaining the common commands you will use to manage backup and restore operations.
Managing Velero using the CLI
Section titled “Managing Velero using the CLI”All Velero operations must be done using the Velero executable. Velero does not include a UI for managing backups and restores. Managing a backup system without a GUI can be a challenge at first, but once you get comfortable with the Velero management commands, it becomes easy to perform operations.
The Velero executable accepts two options:
- Commands
- Flags
A command is an operation such as backup, restore, install, and get. Most initial commands require a second command to make a complete operation. For example, a backup command requires another command, such as create or delete, to form a complete operation.
There are two types of flags – command flags and global flags. Global flags are flags that can be set for any command, while command flags are specific to the command being executed.
Like many CLI tools, Velero includes built-in help for every command. If you forget some syntax or want to know what flags can be used with a command, you can use the -h flag to get help:
velero backup create -hThe following is the abbreviated help output for the backup create command:
Create a backupUsage: velero backup create NAME [flags]Examples: # Create a backup containing all resources. velero backup create backup1 # Create a backup including only the nginx namespace. velero backup create nginx-backup --include-namespaces nginx # Create a backup excluding the velero and default namespaces. velero backup create backup2 --exclude-namespaces velero,default # Create a backup based on a schedule named daily-backup. velero backup create --from-schedule daily-backup # View the YAML for a backup that doesn't snapshot volumes, without sending it to the server. velero backup create backup3 --snapshot-volumes=false -o yaml # Wait for a backup to complete before returning from the command. velero backup create backup4 --waitWe find Velero’s help system to be very helpful; once you get comfortable with Velero’s basics, you will find that the built-in help provides enough information for most commands.
Using common Velero commands
Section titled “Using common Velero commands”Since many readers may be new to Velero, we want to provide a quick overview of the most commonly used commands to get you comfortable with using Velero.
Listing Velero objects
Section titled “Listing Velero objects”As we have mentioned, Velero management is driven by using the CLI. You can imagine that as you create additional backup jobs, it may become difficult to remember what has been created. This is where the get command comes in handy.
The CLI can retrieve, or get, a list of the following Velero objects:
- Backup locations
- Backups
- Plugins
- Restores
- Schedules
- Snapshot locations
As you may expect, executing velero get <object> will return a list of the objects managed by Velero:
velero get backupsHere is the output:
NAME STATUS ERRORS WARNINGSinitial-backup Completed 0 0Each get command will produce a similar output, containing the names of each object and any unique values for the objects. This command is useful for getting a quick look at what objects exist, but it’s usually used before executing the next command, describe.
Retrieving details for a Velero object
Section titled “Retrieving details for a Velero object”After you get the name of the object that you want the details of, you can use the describe command to get the details of the object. Using the output from the get command in the previous section, we want to view the details of the initial-backup job:
velero describe backup initial-backupThe output of the command provides all the details for the requested object. You will find yourself using the describe command to troubleshoot issues such as backup failures.
Creating and deleting objects
Section titled “Creating and deleting objects”Since we have already used the create command a few times, we will focus on the delete command in this section.
To recap, the create command allows you to create objects that will be managed by Velero, including backups, schedules, restores, and locations for backups and snapshots. We have created a backup and a schedule, and in the next section, we will create a restore.
Once an object is created, you may discover that you need to delete it. To delete objects in Velero, you use the delete command, along with the object and name you want to delete.
Since we do not have a backup called sales on our KinD cluster, the example command will not find a backup called sales.
In our get backups output example, we had a backup called sales. To delete that backup, we would execute the following delete command:
velero delete backup salesSince a delete is a one-way operation, you will need to confirm that you want to delete the object. Once you have confirmed the deletion, it may take a few minutes for the object to be removed from Velero since it waits until all associated data is removed:
Are you sure you want to continue (Y/N)? yRequest to delete backup "sales" submitted successfully.The backup will be fully deleted after all associated data (disk snapshots, backup files, restores) are removed.As you can see in the output, when we delete a backup, Velero will delete all of the objects for the backup, including the snapshot’s backup files and restores.
There are additional commands that you can use, but the commands covered in this section are what you really need to get comfortable with Velero. For reference, the list below shows common Velero commands and a brief description of what each command does:
Installing and uninstalling Velero:
velero install: Installs Velero server components into the Kubernetes cluster.
Managing backups:
velero backup create <NAME>: Creates a backup with the specified name.velero backup describe <NAME>: Describes the details of a specific backup.velero backup delete <NAME>: Deletes a specified backup.velero backup logs <NAME>: Displays logs for a specific backup.velero backup download <NAME>: Downloads the backup logs for troubleshooting purposes.velero backup get: Lists all backups.
Managing restores:
velero restore create --from-backup <BACKUP_NAME>: Creates a restore from a specified backup.velero restore describe <NAME>: Describes the details of a specific restore.velero restore delete <NAME>: Deletes a specified restore.velero restore logs <NAME>: Displays logs for a specific restore.velero restore get: Lists all restores.
Scheduling backups:
velero schedule create <NAME> --schedule <CRON_SCHEDULE>: Creates a scheduled backup usingcronsyntax.velero schedule describe <NAME>: Describes the details of a specific schedule.velero schedule delete <NAME>: Deletes a specified schedule.velero schedule get: Lists all schedules.
Managing plugins:
velero plugin add <PLUGIN_IMAGE>: Adds a plugin to the Velero server.velero plugin get: Lists all plugins.
Snapshot locations:
velero snapshot-location create <NAME>: Creates a new snapshot location with the specified name.velero snapshot-location get: Lists all snapshot locations.velero snapshot-location describe <NAME>: Describes the details of a specific snapshot location.velero snapshot-location delete <NAME>: Deletes a specified snapshot location.
Backup locations:
velero backup-location create <NAME>: Establishes a new backup location with the specified name.velero backup-location get: Lists all backup locations.velero backup-location describe <NAME>: Describes the details of a specific backup location.velero backup-location delete <NAME>: Removes a specified backup location.
Managing restic repositories:
velero restic repo get: Lists allresticrepositories.velero restic repo describe <NAME>: Describes the details of a specific restic repository.velero restic repo forget <NAME>: Manually removes restic backup snapshots.velero restic repo prune <NAME>: Removes unused data from a restic repository to free up space.velero restic repo garbage-collect <NAME>: Runs a garbage collection operation on the specified repository.
Utility commands:
velero version: Displays the current version of Velero.velero client config set: Configures the default settings for the Velero client.velero client config get: Displays the current client configuration.velero completion <SHELL>: Generates a shell completion script for the specified shell, enhancing CLI usability.
Now that you can create and schedule backups and know how to use the help system in Velero, we can move on to using a backup to restore objects.
Restoring from a backup
Section titled “Restoring from a backup”In this section, we will explain the process of restoring from a backup using Velero. Having a backup is akin to having car insurance or homeowner’s insurance—it’s essential to have, yet you hope you never need to use it. When the unexpected happens, you’ll be grateful it’s there. In the realm of data backups, finding yourself needing to restore data without a backup is a scenario we often refer to as a “resume-building event.” To run a restore from a backup, you use the create restore command with the --from-backup <backup name> tag.
Earlier in the chapter, we created a single, one-time backup, called initial-backup, which includes every namespace and object in the cluster. If we decided that we needed to restore that backup, we would execute a restore using the Velero CLI:
velero restore create --from-backup initial-backupThe output from the restore command may seem odd:
Restore request "initial-backup-20231207163306" submitted successfully.Run \`velero restore describe initial-backup-20231207163306\` or \`velero restore logs initial-backup-20231207163306\` for more details.At first, it may seem like a backup request was made since Velero replies with "initial-backup-20231207163306" submitted successfully, but you may be wondering why the restore isn’t called initial-backup. Velero uses the backup name to create a restore request, and since we named our backup initial-backup, the restore job name will use that name and append the date and time of the restore request.
You can view the status of the restore using the describe command:
velero restore describe initial-backup-20211001002927Depending on the size of the restore, it may take some time to restore the entire backup. During the restore phase, the status of the backup will be InProgress. Once the restore is complete, the status will change to Completed.
Restoring in action
Section titled “Restoring in action”With all of the theory behind us, let’s use two examples to see Velero restores in action. For the examples, we will start with a simple deployment with a persistent volume that we will delete and restore on the same cluster. The second example will be more complex; we will back up a few namespaces in our main KinD cluster and restore them to a new KinD cluster.
Restoring a deployment from a backup
Section titled “Restoring a deployment from a backup”In the backup section of this chapter, we created a backup of the cluster after we created a busybox deployment with a PVC attached. We added data to the PVC before we backed it up, and now we want to make sure that the backup is complete and that restoring a namespace is successful.
To test the restore, we will simulate a failure by deleting the demo namespace and then use our backup to restore the entire namespace, including the PVC data.
Simulating a failure
Section titled “Simulating a failure”To simulate an event that would require a backup of our namespace, we will delete the entire namespace using kubectl:
kubectl delete ns demoIt may take a minute to delete the objects in the namespace. Once you have returned to a prompt, the deletion should be complete.
Verify that the namespace has been deleted before moving on. Run a kubectl get ns and verify that the demo namespace is no longer listed.
With the confirmation that the demo namespace has been deleted, we will demonstrate how to restore the entire namespace and objects from the backup.
Restoring a namespace
Section titled “Restoring a namespace”Imagine this is a real-life scenario. You receive a phone call that a developer has accidentally deleted every object in their namespace and they do not have the source files.
Of course, you are prepared for this type of event. You have several backup jobs running in your cluster, and you tell the developer that you can restore it to the state it was in last night from a backup.
We want to restore just the one namespace, demo, rather than the entire cluster. We know our backup name is initial-backup, so we will need to use that as our backup file when we execute a restore. To limit the restore to just a namespace, we will add the --include-namespaces demo flag to our command.
velero restore create --from-backup initial-backup --include-namespaces demoRestore request "initial-backup-20231207164723" submitted successfully.Run \`velero restore describe initial-backup-20231207164723\` or \`velero restore logs initial-backup-20231207164723\` for more details.This will start a restore from the initial-backup. It shouldn’t take too long to restore since it’s a single namespace and the PVC only has a few empty files to restore.
First, check to make sure that the namespace has been recreated. If you execute kubectl get ns demo, you should see the demo namespace in the list:
kubectl get ns demoNAME STATUS AGEdemo Active 2m47sGreat! That’s the first step. Now, let’s make sure the pods were restored. We will need the name to look at the PVC contents:
kubectl get pods -n demoNAME READY STATUS RESTARTS AGEbusybox-pvc-f7bfbcc44-vfsnf 1/1 Running 0 4mLooking good so far. Finally, let’s use kubectl exec to look at the /mnt directory in the pod. We are hoping to see the new files we created before the backup:
kubectl exec -it busybox-pvc-f7bfbcc44-vfsnf -n demo -- ls /mnt -laDefaulted container "busybox-pvc" out of: busybox-pvc, restore-wait (init)total 12drwxrwxrwx 3 root root 4096 Dec 7 16:47 .drwxr-xr-x 1 root root 4096 Dec 7 16:47 ..drwxr-xr-x 2 root root 4096 Dec 7 16:47 .velero-rw-r--r-- 1 root root 0 Dec 7 15:48 newfile1-rw-r--r-- 1 root root 0 Dec 7 15:48 newfile2-rw-r--r-- 1 root root 0 Dec 7 16:47 original-dataAs we can see from the output of the ls command, the two files we added before executing the backup, newfile1 and newfile2, are in the pod, proving that the backup works for restoring the namespace, including any persistent data.
Congratulations! You just saved the developer a lot of work because you had a backup of the namespace!
Restoring objects like the previous example is a common exercise, and backing up and restoring in the same cluster is the only thing some operators may think backups are good for. While that may be the most common use case for backups, they can also be used for a number of other activities, like using a backup from one cluster into another, different cluster.
In the next section, we will use a backup from one cluster and restore the data to a different cluster. This is beneficial for a few scenarios, including migrating an application from one cluster to another or restoring the application and data to a development cluster to perform upgrade tests.
Using a backup to create workloads in a new cluster
Section titled “Using a backup to create workloads in a new cluster”Restoring objects in a cluster is just one use case for Velero. While it is the main use case for most users, you can also use your backup files to restore a workload or all workloads on another cluster. This is a useful option if you need to create a new development or disaster recovery cluster.
Remember that Velero backup jobs are only the namespaces and objects in the namespaces. To restore a backup to a new cluster, you must have a running cluster running Velero before you can restore any workloads.
Backing up the cluster
Section titled “Backing up the cluster”By this point in the chapter, we assume that you have seen this process a few times and that you know how to use the Velero CLI. If you need a refresher, you can go back a few pages in the chapter for reference, or use the CLI help function.
For this example, we will not work with any data. Instead, we just want to demonstrate restoring a backup from one cluster to a different cluster.
First, we should create a few namespaces and add some deployments to each one to make it more interesting. We have included a script in the chapter14 folder called create-backup-objects.yaml that will create the namespaces and the objects for you. Run that script to create the namespaces and deployment.
Once the namespaces and deployment have been created, let’s create a new backup called namespace-demo that will back up only the four new namespaces that we created with the script:
velero backup create namespace-demo --include-namespaces=demo1,demo2,demo3,demo4Before moving on, verify that the backup has been completed successfully. You can verify the backup by executing the describe command against the namespace-demo backup:
velero backup describe namespace-demoIn the output, you will see that the backup includes the four namespaces and there are 40 objects in the backup. An abbreviated output is shown below.
Phase: CompletedNamespaces: Included: demo1, demo2, demo3, demo4 Excluded: <none>Resources: Included: * Excluded: <none> Cluster-scoped: autoLabel selector: <none>Or label selector: <none>Storage Location: defaultStarted: 2023-12-07 16:58:02 +0000 UTCCompleted: 2023-12-07 16:58:11 +0000 UTCExpiration: 2024-01-06 16:58:02 +0000 UTCTotal items to be backed up: 36Items backed up: 36Velero-Native Snapshots: <none included> Included: demo1, demo2, demo3, demo4 Excluded: <none>Started: 2021-10-01 00:44:30 +0000 UTCCompleted: 2021-10-01 00:44:42 +0000 UTCExpiration: 2021-10-31 00:44:30 +0000 UTCTotal items to be backed up: 40Items backed up: 40You now have a new backup that contains the four new namespaces and their objects. Now, using this backup, we will restore the four namespaces to a new cluster.
First, we need to deploy a new KinD cluster thar, which will use to restore our demo1, demo2, demo3, and demo4 namespaces.
Building a new cluster
Section titled “Building a new cluster”Since we are only demonstrating how Velero can be used to create workloads on a new cluster from a backup, we will create a simple single-node KinD cluster as our restore point.
This section gets a little complex since you will have two clusters in your kubeconfig file. Follow the steps carefully if you’re new to switching config contexts.
Once we have completed this exercise, we will delete the second cluster since we will not need to have two clusters. This exercise will be interactive. You will need to execute each step:
- Create a new KinD cluster called
velero-restore:kind create cluster --name velero-restore
This will create a new single-node cluster that contains both the control plane and worker node, and it will set your cluster context to the new cluster.
- Once the cluster has deployed, verify that your context has been switched to the
velero-restorecluster:kubectl config get-contexts
The output is as follows:
CURRENT NAME CLUSTER AUTHINFO kind-cluster01 kind-cluster01 kind-cluster01* kind-velero-restore kind-velero-restore kind-velero-restore- Verify that the current context is set to the
kind-velero-restorecluster. You will see an*in the current field of the cluster that is being used. - Finally, verify the namespaces in the cluster using
kubectl. You should only see the default namespaces that are included with a new cluster:NAME STATUS AGEdefault Active 4m51skube-node-lease Active 4m54skube-public Active 4m54skube-system Active 4m54slocal-path-storage Active 4m43s
Now that we have created a new cluster, we can start the process of restoring the workloads. The first step is to install Velero on the new cluster, pointing to the existing S3 bucket as the backup location.
Restoring a backup to the new cluster
Section titled “Restoring a backup to the new cluster”With our new KinD cluster up and running, we need to install Velero to restore our backup. We can use most of the same manifests and settings that we used in the original cluster, but since we are in a different cluster, we need to change the S3 target to the external URL we used to expose MinIO.
Installing Velero in the new cluster
Section titled “Installing Velero in the new cluster”We already have the credentials-velero file in the chapter14 folder, so we can jump right into installing Velero using the velero install command. To follow these steps, you should be in the chapter14 directory:
- Be sure to change the
s3Urlto your MinIO Ingress rule for your original KinD cluster that was created earlier in the chapter. If you forgot the ingress name, change your context tokind-cluster01and usekubectlto look at the rules in theveleronamespace,kubectl get ingress -n velero. This will show you the fullnip.iofor MinIO (remember, don’t use theminio-consolerule):velero install --provider aws --plugins velero/velero-plugin-for-aws:v1.2.0 --bucket velero --secret-file ./credentials-velero --use-volume-snapshots=false --backup-location-config region=minio,s3ForcePathStyle="true",s3Url=http://minio.10.2.1.161.nip.io --use-node-agent --default-volumes-to-fs-backup - The install will take a few minutes, but once the pod is up and running, view the log files to verify that the Velero server is up and running and connected to the S3 target:
kubectl logs deployment/velero -n velero
- If all of your settings were correct, the Velero log will have an entry saying that it has found backups in the backup location that need to be synced with the new Velero server (the number of backups may be different for your KinD cluster):
time="2021-10-01T23:53:30Z" level=info msg="Found 2 backups in the backup location that do not exist in the cluster and need to be synced" backupLocation=default controller=backup-sync logSource="pkg/controller/backup_sync_controller.go:204"
- After confirming the installation, verify that Velero can see the existing backup files using
velero get backups:NAME STATUS ERRORS WARNINGSinitial-backup Completed 0 0namespace-demo Completed 0 0
Your backup list will differ from ours, but you should see the same list that you had in the original cluster.
At this point, we can use any of the backup files to create a restore job in the new cluster.
Restoring a backup in a new cluster
Section titled “Restoring a backup in a new cluster”In this section, we will use the backup that was created in the previous section and restore the workloads to a brand new KinD cluster to simulate a workload migration.
The backup that was created of the original cluster, after we added the namespaces and deployment, was called namespace-demo:
- Using that backup name, we can restore the namespaces and objects by running the
velero create restorecommand:velero create restore --from-backup=namespace-demo - Wait for the restore to complete before moving on to the next step. To verify that the restore was successful, use the
velero describe restorecommand with the name of the restore job that was created when you executed thecreate restorecommand. In our cluster, the restore job was assigned the namenamespace-demo-20211001235926:velero restore describe namespace-demo-20211001235926 - Once the phase has changed from
InProgresstoCompleted, verify that your new cluster has the additional demo namespaces usingkubectl get ns:NAME STATUS AGEcalico-apiserver Active 23mcalico-system Active 24mdefault Active 24mdemo1 Active 15sdemo2 Active 15sdemo3 Active 15sdemo4 Active 15singress-nginx Active 24mkube-node-lease Active 24mkube-public Active 24mkube-system Active 24mlocal-path-storage Active 24mtigera-operator Active 24mvelero Active 5m18s - You will see that the new namespaces were created, and if you look at the pods in each namespace, you will see that each has a pod called
nginx. You can verify that the pods were created usingkubectl get pods. For example, to verify the pods in thedemo1namespace, enter the following:kubectl get pods -n demo1.
The output is as follows:
NAME READY STATUS RESTARTS AGEnginx 1/1 Running 0 3m30sCongratulations! You have successfully restored objects from one cluster into a new cluster.
Deleting the new cluster
Section titled “Deleting the new cluster”Since we do not need two clusters, let’s delete the new KinD cluster that we restored the backup to:
- To delete the cluster, execute the
kind delete clustercommand:kind delete cluster --name velero-restore - Set your current context to the original KinD cluster,
kind-cluster01:kubectl config use-context kind-cluster01
Now that we have cleaned up the temporary second cluster, we have completed the chapter.
Summary
Section titled “Summary”Backing up clusters and workloads is a requirement for any enterprise cluster. Having a backup solution allows you to recover from a disaster or human error. A typical backup solution allows you to restore any Kubernetes object, including namespaces, persistent volumes, RBAC, services, and service accounts. You can also take all of the workloads from one cluster and restore them on a completely different cluster for testing or troubleshooting.
In this chapter, we reviewed how to back up the etcd cluster database using etcdctl and the snapshot feature. We also went into detail on how to install Velero in a cluster to back up and restore workloads. We closed out the chapter by copying workloads from an existing backup by restoring an existing backup on a new cluster.
Coming up in the next chapter, we will introduce you to monitoring your clusters and workloads.
Questions
Section titled “Questions”- True or false – Velero can only use an S3 target to store backup jobs.
- True 2. False
- If you do not have an object storage solution, how can you provide an S3 target using a backend storage solution such as NFS?
- You can’t – there is no way to add anything in front of NFS to present S3. 2. Kubernetes can do this using native CSI features. 3. Install MinIO and use the NFS volumes as persistent disks in the deployment. 4. You don’t need to use an object store; you can use NFS directly with Velero.
- True or false – Velero backups can only be restored on the same cluster where the backup was originally created.
- True 2. False
- What utility can you use to create an
etcdbackup?- Velero.
2. MinIO.
3. There is no reason to back up the
etcddatabase. 4.etcdctl.
- Velero.
2. MinIO.
3. There is no reason to back up the
- Which command will create a scheduled backup that runs every day at 3 A.M.?
velero create backup daily-backup2.velero create @daily backup daily-backup3.velero create backup daily-backup –schedule="@daily3am"4.velero create schedule daily-backup --schedule="0 3 * * *"