etcd 是一个基于 Raft 协议的分布式键值存储系统,主要用于服务发现、配置共享和分布式锁管理。
项目信息
- 项目仓库: https://github.com/etcd-io/etcd
- 当前版本: 3.6.5
- 下载链接 : etcd-v3.6.5-linux-amd64.tar.gz
安装步骤
1. 解压安装包
bash
# 下载并解压到指定目录
tar -xzf etcd-v3.6.5-linux-amd64.tar.gz
sudo mv etcd-v3.6.5-linux-amd64 /usr/local/etcd-v3.6.5/
# 设置文件权限
sudo chown -R $(whoami):$(whoami) /usr/local/etcd-v3.6.5/
chmod +x /usr/local/etcd-v3.6.5/etcd
chmod +x /usr/local/etcd-v3.6.5/etcdctl
2. 创建 systemd 服务实现持久化运行
创建 /etc/systemd/system/etcd.service 文件:
ini
[Unit]
Description=etcd key-value store
After=network.target
[Service]
Type=notify
ExecStart=/usr/local/etcd-v3.6.5/etcd \
--data-dir=/data/etcd \
--logger=zap \
--log-outputs=/data/etcd/etcd.log \
--log-level=info \
--listen-client-urls http://0.0.0.0:2379 \
--advertise-client-urls http://0.0.0.0:2379
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
配置项说明
[Unit] 部分
Description=etcd key-value store: 服务描述信息After=network.target: 网络服务启动后再启动此服务
[Service] 部分
Type=notify: 服务类型为 notify,服务启动完成后会通知 systemdExecStart: 服务启动命令及参数配置:--data-dir=/data/etcd: 指定 etcd 数据存储目录--logger=zap: 使用 zap 作为日志记录器--log-outputs=/data/etcd/etcd.log: 日志输出文件路径--log-level=info: 设置日志级别--listen-client-urls http://0.0.0.0:2379: 监听客户端连接端口--advertise-client-urls http://0.0.0.0:2379: 对外通告的客户端访问地址
Restart=always: 服务异常退出时总是自动重启RestartSec=10: 重启间隔时间(秒)
[Install] 部分
WantedBy=multi-user.target: 服务归属于 multi-user.target
3. 启动服务
bash
# 重新加载 systemd 配置
systemctl daemon-reload
# 设置开机自启
systemctl enable etcd
# 启动服务
systemctl start etcd
# 检查服务状态
systemctl status etcd
验证安装
检查版本一致性
bash
# 检查 etcdctl 和 etcd 版本是否匹配
etcdctl version
etcd --version
集群健康检查
bash
# 检查集群健康状态
etcdctl endpoint health
# 查看集群成员列表
etcdctl member list
输出字段解析
- 成员 ID : 如
8e9e05c52164694d - 成员状态 :
started表示正在运行 - 成员名称 : 如
default - peer URL :
http://localhost:2380,集群内部通信地址 - client URL :
http://0.0.0.0:2379,客户端连接地址 - learner 状态 :
false表示不是 learner 节点
安全配置
默认安全状态
- 无默认密码: etcd 初始安装时没有默认用户名和密码
- 默认无认证: 新安装实例默认无需认证即可访问
启用认证
bash
# 1. 创建 root 用户
etcdctl user add root
# 输入密码并确认
# 2. 启用认证
etcdctl auth enable
# 3. 授权角色权限
etcdctl user grant-role root root
# 4. 查看用户列表
etcdctl user list
⚠️ 重要提醒 : 必须先创建
root用户再启用认证,否则会出现root user does not exist错误。
启用认证后,所有 etcdctl 命令都需要提供凭证:
bash
etcdctl --user root:password command
常见问题解答
Q1: 为什么手动启动进程会消失且数据丢失?
bash
/usr/local/etcd-v3.6.5/etcd --listen-client-urls http://0.0.0.0:2379 --advertise-client-urls http://0.0.0.0:2379 >/dev/null 2>&1 &
原因 : 未指定 --data-dir 参数,etcd 使用临时目录存储数据,进程停止后数据丢失。
解决方案: 明确指定数据目录
bash
/usr/local/etcd-v3.6.5/etcd \
--data-dir=/data/etcd \
--listen-client-urls http://0.0.0.0:2379 \
--advertise-client-urls http://0.0.0.0:2379
Q2: systemd 配置修改后提示需要重新加载?
警告信息:
Warning: etcd.service changed on disk. Run 'systemctl daemon-reload' to reload units.
解决方法:
bash
systemctl daemon-reload
systemctl restart etcd
systemctl status etcd
Q3: 如何查看更多配置选项?
bash
/usr/local/etcd-v3.6.5/etcd --help