版本信息最后核对:2026-12-03
自建 etcd 集群、键值 watch、压缩整理与快照恢复
除了作为 Kubernetes 数据存储,etcd 也常用于自建配置中心、服务发现、分布式锁和选主。本页讲独立部署的 etcd 集群;kubeadm 集群里的 etcd 运维见 etcd,两页不要混用证书路径。
集群成员建议 3 或 5 个,peer 端口 2380,client 端口 2379。每个成员必须显式配置自己的 advertise 地址和完整 initial cluster;新集群统一用 --initial-cluster-state=new,加入已有集群用 existing。
etcd --name etcd1 \
--data-dir /var/lib/etcd \
--listen-client-urls http://0.0.0.0:2379 \
--advertise-client-urls http://10.0.0.11:2379 \
--listen-peer-urls http://0.0.0.0:2380 \
--initial-advertise-peer-urls http://10.0.0.11:2380 \
--initial-cluster etcd1=http://10.0.0.11:2380,etcd2=http://10.0.0.12:2380,etcd3=http://10.0.0.13:2380 \
--initial-cluster-token etcd-cluster \
--initial-cluster-state new \
--quota-backend-bytes 8589934592 \
--auto-compaction-mode periodic \
--auto-compaction-retention 1h
生产必须配 TLS:--cert-file、--key-file、--trusted-ca-file、--client-cert-auth,peer 侧对应 --peer-*。默认后端配额 2GiB,写满触发 NOSPACE 并进入只读。etcd 3.6 起 etcdctl 移除了 snapshot restore/status,要用 etcdutl;3.7 的恢复还支持 --bump-revision 与 --mark-compacted。不同版本参数有差异,以版本为准。
export ETCDCTL_API=3
export ETCDCTL_ENDPOINTS=http://10.0.0.11:2379,http://10.0.0.12:2379,http://10.0.0.13:2379
etcdctl put /app/config '{"debug":false}'
etcdctl get /app/config
etcdctl get /app --prefix --keys-only
etcdctl watch /app --prefix
etcdctl del /app/config
etcdctl endpoint health --cluster
etcdctl endpoint status --write-out=table --cluster
etcdctl member list --write-out=table
etcdctl member add etcd4 --peer-urls=http://10.0.0.14:2380
etcdctl member remove <member-id>
etcdctl compact <revision>
etcdctl defrag --cluster
etcdctl alarm list
etcdctl alarm disarm
etcdctl snapshot save /backup/etcd-$(date +%F).db
etcdutl snapshot status /backup/etcd-$(date +%F).db --write-out=table
etcdutl snapshot restore /backup/etcd-$(date +%F).db --data-dir=/var/lib/etcd-restore
影响与回滚:compact 会删除指定 revision 之前的历史,旧 watcher 会收到 ErrCompacted,不可撤销,执行前先快照。defrag 会阻塞该成员的读写,必须逐成员执行并保持多数派;它只是回收空间,不会改变数据。member remove 会立即降低容错能力,移除到少于多数派时集群只读;操作前备份并确认剩余成员健康。snapshot restore 会回滚到快照时刻,之后的写入全部丢失;恢复到全新空目录,保留旧目录作为回退,所有成员必须恢复到同一时间点。
--advertise-client-urls 写成 127.0.0.1 时其他节点会拿到不可达地址;新集群里混用 initial-cluster-state=existing 或 initial cluster 列表不一致,会启动失败或分裂。snapshot save 用 etcdctl,restore/status 用 etcdutl,照旧教程会报未知子命令。defrag 才会释放。alarm list,再 compact、逐成员 defrag,最后 alarm disarm;顺序反了很快复发。defrag --cluster 会逐个成员执行但仍应避开业务高峰;etcd 对 fsync 延迟极敏感,机械盘或共享存储会拖垮客户端。合上页面,先回答,再展开对照。
compact 之后,从旧 revision 开始的 watcher 会发生什么?defrag 要逐成员执行?NOSPACE 的正确处理顺序是什么?snapshot restore 的数据边界和目录要求是什么?ErrCompacted,因为该 revision 之前的历史已被删除,需要从新 revision 重新 watch。defrag 会阻塞该成员读写;逐成员做可保持多数派。NOSPACE 先定位,再 compact、逐成员 defrag,最后 alarm disarm。
小程序版
微信扫码,随时查命令