如何实现服务发现?介绍Consul和etcd的基本用法
解读
国内一线互联网、金融云及运营商的面试里,“服务发现”已从“加分项”变成“必答题”。
面试官真正想听的是:
- 你能否用 Bash 把“注册-发现-健康检查-故障摘除”跑通,而不是只背概念;
- 在最小依赖(纯 Linux 环境、无 Docker、无 K8s)下,能否用官方二进制 + systemd + 几行 Shell 脚本把集群搭起来;
- 能否把 Consul 与 etcd 的差异落到“命令行参数、KV 路径、TTL 机制”这些可量化的细节上;
- 最后必须给出一段可直接复制到服务器上跑的 Bash 片段,证明你“真的干过”。
知识点
- 服务发现三要素:注册(Register)、发现(Lookup)、健康检查(Health Check)。
- Consul 采用 RAFT + Gossip,内置 DNS/HTTP 双接口,支持 TTL+Script+TCP 三种健康检查;etcd 采用 RAFT,只暴露 gRPC/HTTP API,健康检查需外部实现。
- Consul 的“服务”是 first-class 对象,etcd 的“服务”只是约定俗成的 KV 路径(如 /registry/{ip:port})。
- 国内生产环境常用 systemd 托管进程,用 firewalld 放行 8301/8300/2379/2380 端口;二进制包优先从清华镜像站拉取,避免 GitHub 抖动。
- Bash 实现注册:consul services register 或 etcdctl put + lease grant;发现:consul catalog service 或 etcdctl get –prefix;摘除:consul services deregister 或 lease revoke。
- 必须处理“脑裂”场景:Consul 用 -bootstrap-expect 显式指定票数;etcd 用 –initial-cluster-state existing 防止重复初始化。
答案
下面给出“从零到可运行”的完整 Bash 流程,假设两台 CentOS 7 虚拟机:10.0.0.11(node1)、10.0.0.12(node2)。
所有命令可直接粘贴,无需 Docker、无需 root(仅需 sudo 提权)。
1. 准备
# 两台机器同时执行
sudo yum install -y wget unzip
export CONSUL_VER=1.16.0
export ETCD_VER=3.5.9
# 清华镜像
wget https://mirrors.tuna.tsinghua.edu.cn/github-release/hashicorp/consul/v${CONSUL_VER}/consul_${CONSUL_VER}_linux_amd64.zip
wget https://mirrors.tuna.tsinghua.edu.cn/github-release/etcd-io/etcd/v${ETCD_VER}/etcd-v${ETCD_VER}-linux-amd64.tar.gz
sudo unzip -o consul_${CONSUL_VER}_linux_amd64.zip -d /usr/local/bin/
sudo tar -xzf etcd-v${ETCD_VER}-linux-amd64.tar.gz --strip=1 -C /usr/local/bin/
sudo chmod +x /usr/local/bin/{consul,etcd,etcdctl}
2. 启动 Consul 集群(3 节点演示,这里简写 2 节点,生产必须奇数)
# node1
sudo mkdir -p /etc/consul.d /opt/consul
consul agent -server -ui -bootstrap-expect=2 \
-data-dir=/opt/consul -config-dir=/etc/consul.d \
-bind=10.0.0.11 -client=0.0.0.0 -node=node1 \
-retry-join=10.0.0.12 > consul.log 2>&1 &
# node2
consul agent -server -data-dir=/opt/consul -config-dir=/etc/consul.d \
-bind=10.0.0.12 -client=0.0.0.0 -node=node2 \
-retry-join=10.0.0.11 >> consul.log 2>&1 &
3. 用 Bash 注册一个 Nginx 服务到 Consul
# 任意节点
cat <<EOF | sudo tee /etc/consul.d/nginx.json
{
"service": {
"name": "nginx",
"port": 80,
"check": {
"tcp": "127.0.0.1:80",
"interval": "10s",
"timeout": "2s"
}
}
}
EOF
consul reload # 热加载
4. 发现:一行 Bash 拿到可用实例
consul catalog service nginx -tagged-addresses | awk '{print $2}'
# 输出:10.0.0.11 10.0.0.12(如果都装了 Nginx)
5. 启动 etcd 集群(同样 2 节点示例)
# node1
sudo mkdir -p /opt/etcd
etcd --name node1 \
--initial-advertise-peer-urls http://10.0.0.11:2380 \
--listen-peer-urls http://10.0.0.11:2380 \
--listen-client-urls http://10.0.0.11:2379,http://127.0.0.1:2379 \
--advertise-client-urls http://10.0.0.11:2379 \
--initial-cluster node1=http://10.0.0.11:2380,node2=http://10.0.0.12:2380 \
--initial-cluster-state new \
--data-dir=/opt/etcd > etcd.log 2>&1 &
# node2
etcd --name node2 \
--initial-advertise-peer-urls http://10.0.0.12:2380 \
--listen-peer-urls http://10.0.0.12:2380 \
--listen-client-urls http://10.0.0.12:2379,http://127.0.0.1:2379 \
--advertise-client-urls http://10.0.0.12:2379 \
--initial-cluster node1=http://10.0.0.11:2380,node2=http://10.0.0.12:2380 \
--initial-cluster-state new \
--data-dir=/opt/etcd >> etcd.log 2>&1 &
6. 用 Bash 把同一 Nginx 注册到 etcd(基于 TTL 租约)
# 注册脚本 register_etcd.sh
#!/usr/bin/env bash
IP=$(ip route get 1 | awk '{print $7;exit}')
LEASE=$(etcdctl lease grant 30 | awk '{print $2}')
etcdctl put /registry/nginx/${IP} "${IP}:80" --lease=${LEASE}
# 心跳
while :; do
etcdctl lease keep-alive ${LEASE} >/dev/null 2>&1
sleep 25
done
chmod +x register_etcd.sh
nohup ./register_etcd.sh &
7. 发现:etcd 侧
etcdctl get --prefix /registry/nginx | awk 'NR%2==0'
# 输出:10.0.0.11:80
8. 摘除
# Consul
consul services deregister -id=nginx-10.0.0.11
# etcd
killall register_etcd.sh # 停心跳,30s 后租约过期自动删除
拓展思考
- 如果面试官追问“没有 systemd 怎么保证进程自启?”——可补一个 Bash while true + flock 单例脚本,或直接用 nohup + inotify 监控二进制。
- 遇到“Consul 与 etcd 选哪个”——答:Consul 自带 DNS 接口,适合遗留语言无 SDK 场景;etcd 是 K8s 的“唯一真神”,若公司已有 K8s 直接复用 etcd 可减少运维对象。
- 若问“万级实例如何分页拉取?”——Consul 用 ?near= 参数 + Consistent 模式;etcd 用 –limit –from-key 做范围分段,避免一次性打爆内存。
- 国内合规要求“日志留痕”——把 consul monitor 或 etcd –logger=zap 重定向到 rsyslog,再转存到 ELK,用 Bash 每日归档 gzip。
- 最后可主动抛一个“灰度摘除”方案:利用 Consul 的 /v1/agent/service/register?replace-existing-checks 或 etcd 的 txn 接口,在 Bash 里先下流量权重=0,等待 10s 无连接再删实例,展示你对平滑发布的理解。