# Consul 部署与使用指南

# Consul 部署与使用指南

Consul 是 HashiCorp 公司推出的服务网格解决方案，提供**服务发现**、**健康检查**、**键值存储**和**多数据中心支持**等功能。以下是 Consul 的完整部署与使用手册。

## 一、Consul 部署方案

### 1. 单机模式（开发环境）

```bash
# 下载 Consul (Linux 示例)
wget https://releases.hashicorp.com/consul/1.15.3/consul_1.15.3_linux_amd64.zip
unzip consul_1.15.3_linux_amd64.zip
sudo mv consul /usr/local/bin/

# 启动开发模式
consul agent -dev -client 0.0.0.0
```
访问 `http://<IP>:8500` 进入 Web UI

### 2. 集群模式（生产环境）

#### 服务端节点（至少3台）

```bash
# 启动第一个服务端
consul agent -server -bootstrap-expect=3 \
  -data-dir=/tmp/consul \
  -node=server1 \
  -bind=192.168.1.101 \
  -ui \
  -client=0.0.0.0

# 其他服务端加入集群
consul agent -server -data-dir=/tmp/consul \
  -node=server2 \
  -bind=192.168.1.102 \
  -join=192.168.1.101
```

#### 客户端节点

```bash
consul agent -data-dir=/tmp/consul \
  -node=client1 \
  -bind=192.168.1.201 \
  -join=192.168.1.101
```

### 3. Docker 部署

```bash
docker run -d --name=consul \
  -p 8500:8500 \
  -p 8600:8600/udp \
  consul agent -server -ui -bootstrap-expect=1 -client=0.0.0.0
```

## 二、核心功能使用

### 1. 服务注册

#### 通过配置文件注册（推荐）

创建 `/etc/consul.d/web.json`：
```json
{
  "service": {
    "name": "web",
    "port": 8080,
    "checks": [
      {
        "http": "http://localhost:8080/health",
        "interval": "10s"
      }
    ]
  }
}
```

重新加载配置：
```bash
consul reload
```

#### 通过 API 注册

```bash
curl --request PUT \
  --data @web.json \
  http://localhost:8500/v1/agent/service/register
```

### 2. 服务发现

#### DNS 方式

```bash
dig @127.0.0.1 -p 8600 web.service.consul
```

#### HTTP API 方式

```bash
curl http://localhost:8500/v1/catalog/service/web
```

### 3. 键值存储

```bash
# 写入
consul kv put config/web/max_conns 25

# 读取
consul kv get config/web/max_conns

# 导出所有KV
consul kv export > backup.json
```

### 4. 健康检查

查看节点健康状态：
```bash
consul monitor
```

## 三、生产环境最佳实践

1. **多数据中心部署**：
   ```bash
   consul agent -server -datacenter=dc1 ...
   consul agent -server -datacenter=dc2 ...
   ```

2. **ACL 安全控制**：
   ```bash
   # 启用ACL
   consul acl bootstrap
   ```

3. **自动加密通信**：
   ```bash
   consul tls ca create
   consul tls cert create -server
   ```

4. **监控集成**：
   - 对接 Prometheus
   - 配置 Grafana 仪表盘

## 四、常见问题排查

1. **节点无法加入集群**：
   ```bash
   consul members
   consul operator raft list-peers
   ```

2. **服务注册失败**：
   ```bash
   consul catalog services
   consul monitor -log-level=debug
   ```

3. **性能问题**：
   ```bash
   consul operator raft stats
   ```

## 五、版本升级

```bash
# 滚动升级步骤
consul leave
# 替换新版本二进制
consul agent -config-dir=/etc/consul.d
```

---

通过以上指南，您可以快速部署和管理 Consul 集群。Consul 的强大功能可以帮助您构建可靠的微服务架构，实现服务自动发现和健康管理。