Skip to content
LF Cert Trainer

Lesson 9 · Section 2: Core Concepts

Lesson 9: etcd commands: talking to the cluster's database with etcdctl

The etcdctl and etcdutl commands a cluster administrator needs: how a command reaches etcd, where the certificate flags come from, checking health, reading what Kubernetes stores, and taking and restoring a snapshot. · 17 min read · 4 min video

1/11etcd commands
0:00 / 4:07

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

Why you need etcd commands

On a normal day nobody talks to etcd except the API server. You run kubectl, the API server checks and stores the object, and etcd is an implementation detail. That stops being true in exactly the situations a cluster administrator is paid for:

  • Before an upgrade or a risky change, you want a backup of the whole cluster state. The cluster state is etcd, so the backup is an etcd snapshot.
  • When the control plane misbehaves, kubectl may hang or fail, and you need to know whether etcd itself is healthy without going through the API server.
  • After a disaster, restoring a snapshot is the only way to get the cluster's objects back.

All three are done with etcd's own command line tools, not with kubectl.

The two tools and the API version

etcd ships two tools, and knowing which one a job belongs to removes most of the confusion:

ToolTalks toNeeds certificatesUsed for
etcdctlA running etcd, over the networkYesHealth, members, reading keys, snapshot save, defragmenting
etcdutlFiles on disk, no server involvedNosnapshot status, snapshot restore, offline maintenance

The split is recent. Up to etcd 3.5, etcdctl snapshot restore and etcdctl snapshot status existed and printed a deprecation warning; from etcd 3.6 they are removed, and only etcdutl restores. If a command from an older guide answers unknown command "restore", this is why.

The other thing old guides get wrong is the API version. etcd had a v2 API with a different data model and different commands. Kubernetes only ever uses v3, and etcdctl has defaulted to v3 since etcd 3.4.

API v2 (old guides)API v3 (what you use)
Write and readetcdctl set, get, ls, rmetcdctl put, get, del
Healthetcdctl cluster-healthetcdctl endpoint health
Backupetcdctl backupetcdctl snapshot save
TLS flags--ca-file, --cert-file, --key-file--cacert, --cert, --key

How a command reaches etcd

How an etcdctl command reaches etcdtypesTLS :2379same portTLS fileswritesYoushell on the nodeetcdctlclient, no stateetcd127.0.0.1:2379kube-apiserverthe usual clientCertificates/etc/kubernetes/pkiData directory/var/lib/etcd
How an etcdctl command reaches etcd. etcdctl is only a client. It opens a TLS connection to etcd's client port and proves who it is with a certificate, exactly as the API server does.

Parts:

  • You (shell on the node)
  • etcdctl (client, no state)
  • etcd (127.0.0.1:2379)
  • kube-apiserver (the usual client)
  • Certificates (/etc/kubernetes/pki)
  • Data directory (/var/lib/etcd)

Connections:

  • You to etcdctl: types
  • etcdctl to etcd: TLS :2379
  • kube-apiserver to etcd: same port
  • Certificates to etcdctl: TLS files
  • etcd to Data directory: writes

etcd listens for clients on port 2379 (port 2380 is for the members talking to each other). On a kubeadm cluster it runs as a static Pod on the control plane node, on the host network, so from a shell on that node it is reachable at https://127.0.0.1:2379.

etcd is started with --client-cert-auth=true. That means TLS in both directions: etcdctl checks etcd's certificate against a CA, and etcd refuses any client that does not present a certificate signed by its own CA. That is why a bare etcdctl member list just hangs and times out on a real cluster.

You never have to remember the paths. Each etcdctl flag has a twin among the flags etcd itself was started with, and those are in the static Pod manifest:

etcd server flag (in etcd.yaml)etcdctl flagEnvironment variablekubeadm default
--listen-client-urls--endpointsETCDCTL_ENDPOINTShttps://127.0.0.1:2379
--trusted-ca-file--cacertETCDCTL_CACERT/etc/kubernetes/pki/etcd/ca.crt
--cert-file--certETCDCTL_CERT/etc/kubernetes/pki/etcd/server.crt
--key-file--keyETCDCTL_KEY/etc/kubernetes/pki/etcd/server.key

Every etcdctl flag can be given as an environment variable instead: upper-case the flag name, turn dashes into underscores and put ETCDCTL_ in front.

Under the hood · Why the server's certificate works as a client certificate

It looks odd to hand etcdctl the server's certificate. It works because kubeadm issues server.crt for both server and client authentication, and all etcd asks of a client is a certificate signed by the etcd CA. Two other pairs signed by the same CA work just as well:

  • /etc/kubernetes/pki/etcd/healthcheck-client.crt and .key, made for health checks.
  • /etc/kubernetes/pki/apiserver-etcd-client.crt and .key, the pair the API server itself uses (look for --etcd-certfile in kube-apiserver.yaml).

Note that etcd has its own CA (pki/etcd/ca.crt), separate from the cluster CA in pki/ca.crt. Passing the cluster CA is a classic way to get x509: certificate signed by unknown authority.

Under the hood · Three places to run etcdctl from
  • On the control plane node, if etcdctl is installed there. The certificate files are on the node's disk, so the paths in the table work as they are.
  • Inside the etcd Pod: kubectl -n kube-system exec etcd-controlplane -- etcdctl .... The Pod mounts /etc/kubernetes/pki/etcd at the same path, so the same flags work. The image is minimal and may have no shell, so call etcdctl directly instead of through sh -c, and pass flags rather than relying on your own shell's environment variables. A file you write there (a snapshot, for example) lands inside the container unless you write it under a mounted path such as /var/lib/etcd.
  • Through the container runtime, when the API server is down and kubectl no longer answers: crictl ps --name etcd gives the container id, and crictl exec <id> etcdctl ... runs the command. This works because the kubelet and the runtime keep static Pods running without the API server.

The commands, by job

JobCommandWhat it tells you or does
Is etcd alive?etcdctl endpoint healthCommits a test proposal: healthy means a write still gets through
How is it doing?etcdctl endpoint status -w tableVersion, database size, leader, Raft term and index per endpoint
Who is in the cluster?etcdctl member list -w tableEach member's id, name, peer and client URLs
List keysetcdctl get /registry --prefix --keys-onlyEvery key Kubernetes has written
Read one keyetcdctl get <key>The key and its value (binary for Kubernetes objects)
Follow changesetcdctl watch <key> --prefixPrints every PUT and DELETE as it happens
Back upetcdctl snapshot save <file>A consistent copy of the whole keyspace in one file
Check a backupetcdutl snapshot status <file> -w tableHash, revision, key count and size of the file
Restoreetcdutl snapshot restore <file> --data-dir <dir>Builds a new data directory from the file
Reclaim spaceetcdctl defragGives freed space in the database file back to the disk
Find alarmsetcdctl alarm listShows NOSPACE when the database hit its size quota

Add --cluster to the endpoint commands to ask every member instead of only the endpoints you named. -w sets the output format: simple (the default), table, json or fields.

What Kubernetes stores, and where

Where Kubernetes keeps an object in etcd/registryeverythingpodsresourcedeploymentsresourcesecretsresourceshopnamespaceweb-7d9one key, one object
Where Kubernetes keeps an object in etcd. Every object is one key under /registry: the resource, then the namespace, then the name. Cluster-scoped resources skip the namespace.

Parts:

  • /registry (everything)
  • pods (resource)
  • deployments (resource)
  • secrets (resource)
  • shop (namespace)
  • web-7d9 (one key, one object)

Connections:

  • /registry to pods
  • /registry to deployments
  • /registry to secrets
  • pods to shop
  • shop to web-7d9

The API server keeps every object as one key under the /registry prefix: /registry/<resource>/<namespace>/<name>, or /registry/<resource>/<name> for cluster-scoped resources. A few names are historical: nodes live under /registry/minions, and Services under /registry/services/specs.

The values are not YAML. They are the objects in Kubernetes' binary protobuf encoding, starting with the bytes k8s. You can spot names and image strings in the output, but to read an object you still use kubectl. What etcdctl is good for here is proving that something exists (or does not) at the storage level, counting keys, and watching the API server work.

Under the hood · Why a healthy etcd can still refuse writes

etcd keeps old revisions of every key until they are compacted, and the space compaction frees stays inside the database file until you defragment. The file also has a size quota (--quota-backend-bytes, 2 GB by default). When it is reached, etcd raises a NOSPACE alarm and accepts only reads and deletes: the API server then fails every write with etcdserver: mvcc: database space exceeded, while endpoint health may still look fine.

The API server compacts old revisions on its own every five minutes, so on a Kubernetes cluster the usual fix is etcdctl defrag (one member at a time, because a member blocks while it defragments) followed by etcdctl alarm disarm. Compare DB SIZE with the in-use size in endpoint status to see how much a defrag would reclaim.

Backup and restore

A snapshot out, a new data directory insaverestorepoints toappliesRunning etcd127.0.0.1:2379Snapshot file/opt/backup/etcd.dbNew data dir/var/lib/etcd-restoreetcd.yamlhostPath volumeetcd Podrestarted by kubelet
A snapshot out, a new data directory in. Saving goes through the running server, so it needs certificates. Restoring only reads a file and writes a directory, so it needs none; etcd then has to be pointed at the new directory.

Parts:

  • Running etcd (127.0.0.1:2379)
  • Snapshot file (/opt/backup/etcd.db)
  • New data dir (/var/lib/etcd-restore)
  • etcd.yaml (hostPath volume)
  • etcd Pod (restarted by kubelet)

Connections:

  • Running etcd to Snapshot file: save
  • Snapshot file to New data dir: restore
  • etcd.yaml to New data dir: points to
  • etcd.yaml to etcd Pod: applies

snapshot save asks the running server for a point-in-time copy of its database and streams it into one file. It is safe on a live cluster, and the file carries an integrity hash at the end. snapshot restore does not put data back into a running etcd. It unpacks the file into a new data directory, and you then start etcd on that directory. Until etcd is pointed at it, nothing has changed.

Under the hood · What restore does to cluster identity

A restore writes new member and cluster ids into the new directory, on purpose: a restored member can then never rejoin the old cluster by accident and mix two histories. For a single control plane node the defaults are enough. In a cluster with several etcd members, every member is restored from the same snapshot file with its own --name, --initial-cluster, --initial-cluster-token and --initial-advertise-peer-urls, and all of them start on their new directories together.

A database file copied straight out of a data directory (member/snap/db) has no integrity hash, so restoring it needs --skip-hash-check. A file made with snapshot save never does.

Using it

All four examples run in a root shell on the control plane node of a kubeadm cluster.

Example · Find the flags and check that etcd is healthy

Read the endpoint and the three file paths from the manifest, export them once, then ask.

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

export ETCDCTL_ENDPOINTS=https://127.0.0.1:2379
export ETCDCTL_CACERT=/etc/kubernetes/pki/etcd/ca.crt
export ETCDCTL_CERT=/etc/kubernetes/pki/etcd/server.crt
export ETCDCTL_KEY=/etc/kubernetes/pki/etcd/server.key

etcdctl endpoint health
etcdctl endpoint status -w table
etcdctl member list -w table

The grep also matches --peer-cert-file and --peer-key-file. Those are for member-to-member traffic on port 2380; ignore them. If the manifest is not readable, kubectl -n kube-system describe pod etcd-<node-name> shows the same command line.

Example · See what the API server writes

With the variables from the first example still set, look at the storage behind the objects you know.

etcdctl get /registry --prefix --keys-only | head -20       # a sample of everything
etcdctl get /registry/pods --prefix --keys-only              # every Pod, all namespaces
etcdctl get /registry/pods/shop --prefix --count-only --write-out=fields   # how many in one namespace
etcdctl watch /registry/pods/shop --prefix                   # leave running; Ctrl+C to stop

In a second terminal, run kubectl -n shop run tmp --image=nginx:1.29-alpine and watch several PUT events for the same key arrive: the object is created, then scheduled, then its status is updated. Delete the Pod and a DELETE follows.

Example · Take a snapshot and prove it is good

Save the snapshot to the path the task names, then verify it. A backup you have not checked is a hope, not a backup.

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

The same thing without environment variables, as one command you can paste anywhere:

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

snapshot status needs no certificates, because it only reads the file. A snapshot is a full copy of the cluster's objects, Secrets included, so treat the file as you would the cluster's credentials.

Example · Restore a snapshot on a kubeadm control plane

Restore into a new directory, then make etcd use it.

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

Now edit /etc/kubernetes/manifests/etcd.yaml and change the hostPath of the data volume. Leave the --data-dir flag and the volumeMounts alone: the container still sees /var/lib/etcd, it is the directory on the host behind that path that 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; give it a minute.

crictl ps --name etcd            # the container is back and its age is seconds
etcdctl endpoint health
kubectl get pods -A              # objects are as they were at the snapshot

The other control plane components were talking to the old data. If kubectl shows stale or odd state, restart them by moving their manifests out of /etc/kubernetes/manifests and back, and run systemctl restart kubelet.

Tricks

Common mistakes

  • A command that hangs, then context deadline exceeded. The TLS flags are missing, or the endpoint says http:// instead of https://. etcd does not answer clients it cannot authenticate.
  • certificate signed by unknown authority. You passed the cluster CA (pki/ca.crt) instead of etcd's own CA (pki/etcd/ca.crt).
  • unknown command "restore" or "status". The etcdctl on this machine is 3.6 or newer: use etcdutl for snapshot restore and snapshot status.
  • Restoring into the live data directory. Restore refuses a directory that already has data, and deleting /var/lib/etcd under a running etcd destroys the cluster. Always restore to a new directory and switch over.
  • Restoring and stopping there. The restore only creates a directory. Until the hostPath in etcd.yaml points at it, etcd keeps serving the old data and kubectl shows no change.
  • Changing the wrong line in the manifest. Editing --data-dir without the matching volume and mount makes etcd write inside the container, where the data is lost on the next restart. Change the hostPath only.
  • Saving the snapshot inside the container. With kubectl exec, /opt/backup/etcd.db is a path in the container, not on the node, and it disappears with the container.

Recap

  • etcdctl talks to a running etcd and needs an endpoint, a CA, a certificate and a key; etcdutl works on files and needs none of them.
  • All four values are in /etc/kubernetes/manifests/etcd.yaml; export them as ETCDCTL_ variables once.
  • endpoint health, endpoint status -w table and member list answer whether etcd is well.
  • Kubernetes objects are keys under /registry; read them freely, but leave the writing to the API server.
  • Backup is etcdctl snapshot save; restore is etcdutl snapshot restore into a new directory, then point the etcd manifest's hostPath at it.

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

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

  • Talk to the cluster's etcd with etcdctl: identify the member, find the key behind an object, read what etcd really stores for a Secret, and ask the server about itself.

    Investigate · Level 2 · standard · target 20 min

Discussion

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