Skip to content
LF Cert Trainer

Lesson 66 · Section 6: Cluster Maintenance

Lesson 66: Backup and restore methods: what to save, and how to get a cluster back

The three things a cluster backup must cover, the three ways to save the cluster's objects (files in Git, an export through the API server, an etcd snapshot), when each one fits, and the full restore routine on a kubeadm control plane. · 18 min read · 4 min video

1/11Backup and restore methods
0:00 / 4:27

Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.

Why you need a backup plan

Kubernetes repairs a lot by itself: a crashed container restarts, a lost Pod is replaced, a dead node's work moves elsewhere. All of that repair is driven by the objects stored in the cluster. Nothing repairs the objects themselves. If the control plane's disk dies, if an upgrade corrupts etcd, or if somebody runs kubectl delete namespace against the wrong cluster, the cluster cannot heal, because the description of what "healthy" looks like is exactly what was lost.

So a cluster administrator answers two questions before that day comes: what has to be saved, and which method saves it on this particular cluster.

What has to be saved

Three things to back up, three different backupslive inlives inlive onsaved bysaved bysaved byCluster objectsDeployments, SecretsApplication datadatabase rows, uploadsNode filescertificates, manifestsetcd/var/lib/etcdVolumesdisks and shares/etc/kubernetescontrol plane disketcd snapshotor an API exportVolume snapshotor a storage backupFile copytar, rsync
Three things to back up, three different backups. A cluster keeps its state in three places. No single backup covers all of them: an etcd snapshot holds the objects, but not the data inside volumes and not the files on the control plane's disk.

Parts:

  • Cluster objects (Deployments, Secrets)
  • Application data (database rows, uploads)
  • Node files (certificates, manifests)
  • etcd (/var/lib/etcd)
  • Volumes (disks and shares)
  • /etc/kubernetes (control plane disk)
  • etcd snapshot (or an API export)
  • Volume snapshot (or a storage backup)
  • File copy (tar, rsync)

Connections:

  • Cluster objects to etcd: live in
  • Application data to Volumes: lives in
  • Node files to /etc/kubernetes: live on
  • etcd to etcd snapshot: saved by
  • Volumes to Volume snapshot: saved by
  • /etc/kubernetes to File copy: saved by
WhatWhere it livesWhat is lost without itHow to back it up
Cluster objects: Deployments, Services, ConfigMaps, Secrets, RBAC rules, custom resourcesetcdEvery workload definition, all access rules, all configurationetcd snapshot, an export through the API server, or the files in Git
Application data: database rows, uploaded files, queuesPersistentVolumes (disks, network shares)The data itself, even if every object comes backVolume snapshots, the storage system's backups, the application's own dump
Node files: the CA and its keys, static Pod manifests, the encryption configuration/etc/kubernetes on the control planeThe cluster's identity: every kubeconfig and node stops being trustedA plain file copy, kept somewhere safe

The middle row is the one people forget. A PersistentVolume object in etcd is only a pointer to a disk. A snapshot of etcd saves the pointer and nothing the disk contains. Restoring it after the disk is gone gives you a healthy-looking PVC bound to nothing.

Worker nodes are not on the list on purpose. A worker holds no state that is not rebuilt from the control plane: replace it and join the new one with kubeadm join.

Under the hood · Which files on the control plane matter
  • /etc/kubernetes/pki/: the cluster CA, the etcd CA, the front-proxy CA and the service account key pair (sa.key, sa.pub). kubeadm can issue new leaf certificates at any time, but only from these CA keys. With a new CA, every kubeconfig, every kubelet and every service account token is invalid.
  • The encryption configuration file, if Secrets are encrypted at rest (look for --encryption-provider-config in kube-apiserver.yaml). An etcd snapshot of an encrypted cluster holds encrypted Secrets, and only the key in this file can read them.
  • /etc/kubernetes/manifests/: the static Pod manifests, with every flag the control plane was started with.
  • /etc/kubernetes/*.conf: the kubeconfigs of the admin, the controller manager, the scheduler and the kubelet. These can be regenerated from the CA, so they are convenient rather than essential.

These files are secrets in the strict sense. Whoever holds ca.key can issue themselves a cluster-admin certificate, so store the copy at least as carefully as the snapshot.

Three ways to save the objects

Three places to take the objects fromapplystoresread objectscopy databaseFiles in Gitwhat you appliedkube-apiserverevery object, as YAMLetcdthe stored stateAPI exportkubectl get, VeleroSnapshot fileetcdctl snapshot save
Three places to take the objects from. Every object passes the same chain: a file, the API server, etcd. You can keep a copy at each stop. The further right you take it, the more complete it is, and the more access you need.

Parts:

  • Files in Git (what you applied)
  • kube-apiserver (every object, as YAML)
  • etcd (the stored state)
  • API export (kubectl get, Velero)
  • Snapshot file (etcdctl snapshot save)

Connections:

  • Files in Git to kube-apiserver: apply
  • kube-apiserver to etcd: stores
  • kube-apiserver to API export: read objects
  • etcd to Snapshot file: copy database

Every object travels the same road: it starts as a file, the API server validates and stores it, and it ends up in etcd. You can keep a copy at each of the three stops.

1. The files themselves, in Git

If every object is created with kubectl apply -f from files kept in a repository, the repository is a backup. Losing the cluster means building a new one and applying the files again. This is the declarative way of working, and it gives you history, review and an answer to "who changed this" for free.

Its weakness is everything that did not come from a file: an object made with kubectl create or kubectl run, a quick kubectl edit or kubectl scale during an incident, a Secret typed in by hand. None of that is in Git, and you will not know what is missing until you need it.

2. An export through the API server

Instead of trusting that the files are complete, ask the cluster what it actually holds:

kubectl get all --all-namespaces -o yaml > all-objects.yaml

This catches objects however they were created. It also needs nothing but API access, which makes it the only method on a managed cluster (EKS, AKS, GKE and the like), where the provider runs etcd and gives you no way in.

A complete export has to walk every resource type the cluster serves (kubectl api-resources --verbs=list), in every namespace, and then clean the result: exported objects carry status, uid, resourceVersion and assigned IPs that a new cluster will refuse or ignore. Doing this well is the job of dedicated backup tools. Velero is the best known open source one: it reads objects through the API server, stores them in object storage, can snapshot the volumes they use, runs on a schedule, and restores a whole cluster, one namespace or a single resource type.

3. A snapshot of etcd

The third stop is the database. One command asks the running etcd for a consistent copy of everything and writes it into a single file:

etcdctl snapshot save /opt/backup/etcd.db

The file holds every object of every type, exactly as stored, including things no export thinks of: Events, Leases, the kubeadm configuration, the bootstrap tokens. Restoring it gives back the cluster as it was at that moment, in one step.

The price is access. You need a shell on a control plane node, the etcd client certificates, and the right to restart the control plane. On a managed cluster you have none of these.

Which one to use

Files in GitAPI exportetcd snapshot
CapturesWhat you wrote in filesEvery object the export asks forEverything, byte for byte
MissesImperative changes, hand-made objectsTypes the export skips; volume data unless the tool adds itVolume data, node files
Access neededThe repositoryThe API serverA control plane node and etcd certificates
Works on managed clustersYesYesNo
Restore one namespace or objectYesYesNo, the whole cluster or nothing
Restore into a different clusterYesYesOnly as a replacement of the same cluster
Typical useDay-to-day source of truthMigration, managed clusters, partial restoresDisaster recovery, before an upgrade

These are layers, not rivals. A well run cluster has its manifests in Git, a scheduled etcd snapshot or Velero backup for what Git misses, and volume backups for the data. For the CKA exam, the method you are asked to perform by hand is the etcd snapshot.

Under the hood · A fourth way: copying the data directory

etcd's whole state is the directory named by --data-dir (/var/lib/etcd on kubeadm). You can back that up as files too, in two ways.

  • A storage-level snapshot of the disk or volume that holds the directory (LVM, a cloud disk snapshot). The Kubernetes documentation lists this as the second supported method.
  • A copy of the database file member/snap/db. Take it only while etcd is stopped, or the copy may be torn mid-write. Such a file has no integrity hash, so restoring it needs etcdutl snapshot restore --skip-hash-check.

etcdctl snapshot save is preferred whenever etcd is running: it is consistent by construction, it does not disturb the member, and the file checks itself. The file copy is what you fall back on when etcd will not start at all and the directory is the only thing left.

How a restore works

Restoring an etcd snapshot on a kubeadm control planerestorepoints tomountedreconnectsSnapshot file/opt/backup/etcd.dbNew data dir/var/lib/etcd-restoreetcd Podrecreated by kubeletetcd.yamlhostPath changedkube-apiserverstop first, start last
Restoring an etcd snapshot on a kubeadm control plane. A restore never writes into the running etcd. It builds a new data directory from the file, and etcd is then started on that directory. The API server is stopped first and started last.

Parts:

  • Snapshot file (/opt/backup/etcd.db)
  • New data dir (/var/lib/etcd-restore)
  • etcd Pod (recreated by kubelet)
  • etcd.yaml (hostPath changed)
  • kube-apiserver (stop first, start last)

Connections:

  • Snapshot file to New data dir: restore
  • etcd.yaml to New data dir: points to
  • New data dir to etcd Pod: mounted
  • kube-apiserver to etcd Pod: reconnects

The backup command talks to a running server. The restore command does not. etcdutl snapshot restore reads the snapshot file and writes a new data directory; no server is involved and no certificates are needed. Nothing in the cluster changes until etcd is started on that directory. On a kubeadm cluster that means changing one line in etcd's static Pod manifest and letting the kubelet recreate the Pod.

Three design choices explain the routine:

  • Why a new directory? Restore refuses to write into a directory that already holds data, and the old directory is your way back if the snapshot turns out to be the wrong one. Keep it until the cluster is verified.
  • Why stop the API server? The API server and the controllers cache what they read. If etcd's content jumps back in time underneath them, they act on a mix of old and new state. The Kubernetes documentation is explicit: stop all API servers, restore etcd, start the API servers again, and then restart the scheduler, the controller manager and the kubelets so that none of them trusts stale data.
  • Why does the restored etcd get a new identity? Restore writes fresh cluster and member ids into the new directory. A restored member can then never rejoin the old cluster by accident and mix two histories.
Under the hood · Stacked or external etcd: find out first

kubeadm normally runs etcd as a static Pod on each control plane node ("stacked" etcd). Some clusters run it as a system service on the control plane or on separate machines ("external" etcd). The backup command is the same; the restore's last step is not.

kubectl -n kube-system get pods | grep etcd                       # a Pod: stacked
grep etcd-servers /etc/kubernetes/manifests/kube-apiserver.yaml   # where the API server finds etcd
systemctl cat etcd 2>/dev/null | grep -E 'data-dir|cert|listen'   # a unit file: external

With an external etcd, the endpoint and certificate paths come from the unit file or from the API server's --etcd-servers, --etcd-cafile, --etcd-certfile and --etcd-keyfile flags. After the restore you point the service at the new directory instead of editing a manifest:

chown -R etcd:etcd /var/lib/etcd-restore        # the service does not run as root
vi /etc/systemd/system/etcd.service             # --data-dir=/var/lib/etcd-restore
systemctl daemon-reload && systemctl restart etcd

The forgotten chown is the classic failure: etcd then fails to start with a permission error in journalctl -u etcd.

Under the hood · Restoring a control plane with several etcd members

With three or five members, all of them are restored from the same snapshot file, each on its own node, each with its own --name and --initial-advertise-peer-urls and the same --initial-cluster and --initial-cluster-token. Then all members start on their new directories together and form a new cluster. Restoring only one member and letting it rejoin the others does not work: the others still hold the newer history and the restored member has a different cluster id.

Using it

The etcd examples run in a root shell on the control plane node of a kubeadm cluster with stacked etcd. The details of every etcdctl and etcdutl flag are the subject of the next lesson; here the point is the routine.

Example · Export objects through the API server

A quick export of the common workload objects, then the gaps filled in by naming the missing types.

kubectl get all --all-namespaces -o yaml > /opt/backup/all-objects.yaml

kubectl get configmaps,secrets,persistentvolumeclaims,ingresses,serviceaccounts,roles,rolebindings \
  --all-namespaces -o yaml > /opt/backup/namespaced-extras.yaml

kubectl get namespaces,persistentvolumes,storageclasses,clusterroles,clusterrolebindings,customresourcedefinitions \
  -o yaml > /opt/backup/cluster-scoped.yaml

To restore one application into a working cluster, apply the piece you need:

kubectl -n shop get deployment web -o yaml > web.yaml      # before the risky change
kubectl apply -f web.yaml                                  # after it went wrong

An exported Secret is only base64 encoded, so these files need the same protection as the cluster itself.

Example · Back up etcd before a risky change

Read the four values from the manifest, save the snapshot where the task says, and verify it.

grep -E 'listen-client-urls|trusted-ca-file|cert-file|key-file' /etc/kubernetes/manifests/etcd.yaml

etcdctl --endpoints=https://127.0.0.1:2379 \
  --cacert=/etc/kubernetes/pki/etcd/ca.crt \
  --cert=/etc/kubernetes/pki/etcd/server.crt \
  --key=/etc/kubernetes/pki/etcd/server.key \
  snapshot save /opt/backup/etcd.db

etcdutl snapshot status /opt/backup/etcd.db -w table

The grep also prints --peer-cert-file and --peer-key-file; those belong to the traffic between etcd members and are not what you want. snapshot status shows a hash, a revision and a key count: a key count in the hundreds or more tells you the file is a real cluster and not an empty database.

Then copy the node files next to it, so that the backup is usable on a rebuilt machine:

tar -czf /opt/backup/kubernetes-files.tgz /etc/kubernetes/pki /etc/kubernetes/manifests

Example · Restore the snapshot on a kubeadm control plane

Stop the API server, build the new directory, switch etcd over, start the API server.

mv /etc/kubernetes/manifests/kube-apiserver.yaml /root/        # the kubelet stops the API server
crictl ps --name kube-apiserver                                # wait until the list is empty

etcdutl snapshot restore /opt/backup/etcd.db --data-dir /var/lib/etcd-restore

Edit /etc/kubernetes/manifests/etcd.yaml and change the hostPath of the data volume. Leave the --data-dir flag and the volumeMounts as they are: the container still sees /var/lib/etcd, and only the host directory behind that path changes.

  volumes:
    - hostPath:
        path: /var/lib/etcd-restore     # was /var/lib/etcd
        type: DirectoryOrCreate
      name: etcd-data

The kubelet notices the changed manifest and recreates the etcd Pod. Wait for it, then bring the API server back.

crictl ps --name etcd                                          # a new container, a few seconds old
mv /root/kube-apiserver.yaml /etc/kubernetes/manifests/
kubectl get pods -A                                            # may take a minute to answer

Finally, make the other components forget what they cached. Moving a static Pod's manifest out and back restarts it:

cd /etc/kubernetes/manifests
mv kube-scheduler.yaml kube-controller-manager.yaml /root/ && sleep 20
mv /root/kube-scheduler.yaml /root/kube-controller-manager.yaml .
systemctl restart kubelet

Verify with something the task or your notes name: a Deployment that existed at snapshot time is back, one created afterwards is gone.

Example · Prove that the backup works

Take a snapshot, change something, restore, and see the change undone. This is the only real test of a backup, and it is a good drill on a practice cluster.

etcdctl snapshot save /opt/backup/drill.db          # with the endpoint and certificate flags
kubectl create namespace after-the-snapshot

# ... restore /opt/backup/drill.db with the steps of the previous example ...

kubectl get namespace after-the-snapshot            # Error from server (NotFound)

The namespace created after the snapshot is gone: the cluster is back at the snapshot's moment.

Tricks

Common mistakes

  • Believing kubectl get all is a backup. It skips ConfigMaps, Secrets, PVCs, RBAC, cluster-scoped objects and custom resources.
  • Believing an etcd snapshot includes application data. It holds the PersistentVolume objects, not what is on the volumes.
  • Saving a snapshot without the TLS flags. The command hangs and ends with context deadline exceeded; etcd does not answer clients it cannot authenticate.
  • Restoring and stopping there. The restore only creates a directory. Until the hostPath in etcd.yaml (or --data-dir of an external etcd's service) points at it, etcd keeps serving the old data.
  • Editing --data-dir in the static Pod manifest instead of the hostPath. Without a matching volume and mount, etcd writes inside the container and the data is lost at the next restart.
  • Forgetting ownership on an external etcd. The restored directory belongs to root, the service runs as etcd, and it fails to start until you chown -R etcd:etcd the directory.
  • Keeping the snapshot only on the control plane node. The disk that fails takes the backup with it. Copy it off the machine, together with /etc/kubernetes/pki and the encryption configuration.
  • Using etcdctl snapshot restore from an old guide. From etcd 3.6 that subcommand is gone; restore with etcdutl.

Recap

  • Back up three things: the objects in etcd, the application data in volumes, and the files under /etc/kubernetes on the control plane.
  • Objects can be saved at three stops: files in Git, an export through the API server (kubectl get, Velero), or an etcd snapshot.
  • On a managed cluster you cannot reach etcd, so the API export is the only choice; on a cluster you run yourself, the etcd snapshot is the complete one.
  • etcdctl snapshot save backs up a running etcd; etcdutl snapshot restore builds a new data directory, and the etcd manifest's hostPath must then point at it.
  • Stop the API server before a restore, start it after, and remember that a restore sends the whole cluster back in time, without the volume data.

Official docs

Quiz: check what you learned

5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.

Sign in to take the quiz and keep your score.

Practise: try it on a real cluster

2 hands-on labs for this lesson. You get goals, not steps: any solution that reaches them passes.

  • A namespace was deleted and only an etcd snapshot remembers it. Save the present first, then restore the whole cluster from the snapshot and get the control plane running on the restored data.

    Fix · Level 3 · challenge · target 25 min

  • Section capstone on a kubeadm cluster. Empty a node for repair without hurting a protected app, save an etcd snapshot, unpack an older snapshot next to the live data, and upgrade the control plane node to the next Kubernetes version.

    Build · Level 3 · challenge · target 45 min

Discussion

Learners ask and answer questions here. Sign in to read and join the discussion.