一、高可用概述

1.1 什么是高可用

高可用(High Availability,HA)是指系统在面对硬件故障、软件异常、网络中断等问题时,仍能持续提供服务的能力。核心目标是减少停机时间,保障业务连续性。

1.2 可用性指标

可用性等级

年停机时间

常见场景

99%(2个9)

3.65 天

普通内部系统

99.9%(3个9)

8.76 小时

一般互联网业务

99.99%(4个9)

52.6 分钟

核心业务系统

99.999%(5个9)

5.26 分钟

金融/电信核心系统

计算公式:可用性 = (总时间 - 停机时间) / 总时间 × 100%

1.3 单点故障(SPOF)

单点故障是指系统中某个组件一旦失效,整个系统就会停止服务的薄弱环节。常见单点故障包括:

  • 单台 Web 服务器:服务器宕机,网站不可访问

  • 单个数据库实例:数据库故障,应用无法读写

  • 单条网络链路:网络中断,服务不可达

  • 单个 DNS 解析:DNS 故障,域名无法解析

消除单点故障是高可用设计的核心任务。


二、LVS(Linux Virtual Server)

2.1 LVS 简介

LVS 是 Linux 内核级的四层(传输层)负载均衡器,性能极高,单机可处理百万级并发连接。

2.2 三种工作模式

LVS-DR(Direct Routing,直接路由)

最常用模式。负载均衡器只修改目标 MAC 地址,响应包直接由 Real Server 返回客户端,不经过负载均衡器。

# Director 配置
ipvsadm -A -t 192.168.1.100:80 -s rr
ipvsadm -a -t 192.168.1.100:80 -r 192.168.1.101:80 -g
ipvsadm -a -t 192.168.1.100:80 -r 192.168.1.102:80 -g

# Real Server 配置(绑定 VIP 到 lo 并抑制 ARP)
ip addr add 192.168.1.100/32 dev lo
echo 1 > /proc/sys/net/ipv4/conf/lo/arp_ignore
echo 2 > /proc/sys/net/ipv4/conf/lo/arp_announce
echo 1 > /proc/sys/net/ipv4/conf/all/arp_ignore
echo 2 > /proc/sys/net/ipv4/conf/all/arp_announce

优点:性能最高,响应不经过 Director。缺点:Director 和 Real Server 必须在同一二层网络。

LVS-NAT(Network Address Translation)

负载均衡器做地址转换,请求和响应都经过 Director。

# Director 配置(需开启 IP 转发)
echo 1 > /proc/sys/net/ipv4/ip_forward
ipvsadm -A -t 10.0.0.1:80 -s rr
ipvsadm -a -t 10.0.0.1:80 -r 192.168.1.101:80 -m
ipvsadm -a -t 10.0.0.1:80 -r 192.168.1.102:80 -m

# Real Server 网关指向 Director 内网 IP
ip route add default via 192.168.1.1

优点:配置简单,支持端口映射。缺点:Director 成为瓶颈。

LVS-TUN(IP Tunneling,IP 隧道)

通过 IP 隧道封装请求包转发给 Real Server,响应直接返回客户端。

ipvsadm -A -t 192.168.1.100:80 -s rr
ipvsadm -a -t 192.168.1.100:80 -r 192.168.1.101:80 -i
ipvsadm -a -t 192.168.1.100:80 -r 192.168.1.102:80 -i

# Real Server 配置隧道接口
ip tunnel add tunl0 mode ipip
ip link set tunl0 up
ip addr add 192.168.1.100/32 dev tunl0

2.3 调度算法

算法

说明

适用场景

rr(Round Robin)

轮询

服务器性能均匀

wrr(Weighted Round Robin)

加权轮询

服务器性能不均

lc(Least Connection)

最少连接

长连接场景

wlc(Weighted Least Connection)

加权最少连接(默认)

通用推荐

sh(Source Hashing)

源地址哈希

需要会话保持

dh(Destination Hashing)

目标地址哈希

缓存场景


三、HAProxy

3.1 HAProxy 简介

HAProxy 是一款高性能的四层/七层负载均衡器和代理服务器,广泛应用于企业生产环境。

3.2 核心配置

# /etc/haproxy/haproxy.cfg

global
    log /dev/log local0
    maxconn 50000
    user haproxy
    group haproxy
    daemon
    stats socket /var/run/haproxy.sock mode 660 level admin

defaults
    mode http
    log global
    option httplog
    option dontlognull
    option forwardfor
    timeout connect 5s
    timeout client 30s
    timeout server 30s
    retries 3

# 前端定义
frontend http_front
    bind *:80
    bind *:443 ssl crt /etc/ssl/certs/server.pem
    redirect scheme https if !{ ssl_fc }
    
    # ACL 路由
    acl is_api path_beg /api
    acl is_static path_end .jpg .png .css .js
    
    use_backend api_servers if is_api
    use_backend static_servers if is_static
    default_backend web_servers

# 后端定义
backend web_servers
    balance roundrobin
    option httpchk GET /health HTTP/1.1\r\nHost:\ localhost
    http-check expect status 200
    
    server web1 192.168.1.101:8080 check inter 3s fall 3 rise 2 weight 5
    server web2 192.168.1.102:8080 check inter 3s fall 3 rise 2 weight 5
    server web3 192.168.1.103:8080 check inter 3s fall 3 rise 2 weight 3 backup

backend api_servers
    balance leastconn
    option httpchk GET /api/health
    
    server api1 192.168.1.201:9090 check
    server api2 192.168.1.202:9090 check

backend static_servers
    balance uri
    server static1 192.168.1.301:80 check
    server static2 192.168.1.302:80 check

3.3 负载均衡算法

算法

配置关键字

说明

轮询

balance roundrobin

默认,按权重轮流分配

最少连接

balance leastconn

分配给连接数最少的服务器

源地址哈希

balance source

同一客户端 IP 固定后端

URI 哈希

balance uri

同一 URI 固定后端(适合缓存)

HTTP 头哈希

balance hdr(Host)

按请求头哈希分配

3.4 健康检查配置

# TCP 检查
option tcp-check
tcp-check connect
tcp-check send QUIT\r\n
tcp-check expect string +OK

# HTTP 检查
option httpchk GET /health
http-check expect status 200

# 自定义检查间隔
server backend1 192.168.1.101:80 check inter 5s fall 3 rise 2

3.5 SSL 终止

frontend https_front
    bind *:443 ssl crt /etc/ssl/certs/combined.pem alpn h2,http/1.1
    
    # 启用 HTTP/2
    # 后端使用 HTTP 明文通信
    default_backend web_servers
    
backend web_servers
    server web1 192.168.1.101:80 check

证书合并命令:

cat server.crt server.key > combined.pem
chmod 600 combined.pem

3.6 统计页面

listen stats
    bind *:8404
    mode http
    stats enable
    stats uri /stats
    stats refresh 10s
    stats admin if TRUE
    stats auth admin:SecurePass123

访问 http://<haproxy-ip>:8404/stats 查看实时状态,支持在线上下线后端服务器。


四、Nginx 负载均衡

4.1 Upstream 配置

# /etc/nginx/conf.d/upstream.conf

upstream web_backend {
    # 加权轮询(默认)
    server 192.168.1.101:8080 weight=5;
    server 192.168.1.102:8080 weight=3;
    server 192.168.1.103:8080 weight=2;

    # 备用服务器
    server 192.168.1.104:8080 backup;

    # 最大失败次数和超时
    server 192.168.1.105:8080 max_fails=3 fail_timeout=30s;

    # 长连接池
    keepalive 32;
}

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://web_backend;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
    }
}

4.2 负载均衡算法

# 最少连接
upstream backend {
    least_conn;
    server 192.168.1.101:8080;
    server 192.168.1.102:8080;
}

# IP 哈希(会话保持)
upstream backend {
    ip_hash;
    server 192.168.1.101:8080;
    server 192.168.1.102:8080;
}

# 一致性哈希(需第三方模块或 Nginx Plus)
upstream backend {
    hash $request_uri consistent;
    server 192.168.1.101:8080;
    server 192.168.1.102:8080;
}

4.3 会话保持方案

# 方案一:基于 IP 哈希
upstream backend {
    ip_hash;
    server 192.168.1.101:8080;
    server 192.168.1.102:8080;
}

# 方案二:基于 Cookie(Nginx Plus 或 sticky 模块)
upstream backend {
    sticky cookie srv_id expires=1h domain=.example.com path=/;
    server 192.168.1.101:8080;
    server 192.168.1.102:8080;
}

# 方案三:基于请求头
upstream backend {
    hash $http_x_session_id consistent;
    server 192.168.1.101:8080;
    server 192.168.1.102:8080;
}

4.4 故障转移配置

upstream backend {
    server 192.168.1.101:8080;
    server 192.168.1.102:8080;
    server 192.168.1.103:8080 backup;
}

server {
    listen 80;
    location / {
        proxy_pass http://backend;
        proxy_next_upstream error timeout http_500 http_502 http_503 http_504;
        proxy_next_upstream_tries 3;
        proxy_next_upstream_timeout 10s;
        proxy_connect_timeout 5s;
        proxy_read_timeout 30s;
    }
}

五、Keepalived

5.1 Keepalived 简介

Keepalived 基于 VRRP(Virtual Router Redundancy Protocol)协议实现 IP 地址漂移,配合健康检查实现服务高可用。

5.2 VRRP 与 VIP

VRRP 将多台服务器组成一个虚拟路由组,通过竞选机制选出 Master 节点持有 VIP(Virtual IP)。当 Master 故障时,Backup 节点接管 VIP。

5.3 主节点配置

# /etc/keepalived/keepalived.conf (Master)

global_defs {
    router_id LVS_MASTER
    script_user root
    enable_script_security
}

vrrp_script check_nginx {
    script "/etc/keepalived/check_nginx.sh"
    interval 2
    weight -20
    fall 3
    rise 2
}

vrrp_instance VI_1 {
    state MASTER
    interface eth0
    virtual_router_id 51
    priority 100
    advert_int 1
    
    authentication {
        auth_type PASS
        auth_pass MySecretKey
    }
    
    virtual_ipaddress {
        192.168.1.200/24 dev eth0
    }
    
    track_script {
        check_nginx
    }
    
    notify_master "/etc/keepalived/notify.sh master"
    notify_backup "/etc/keepalived/notify.sh backup"
    notify_fault  "/etc/keepalived/notify.sh fault"
}

5.4 备节点配置

# /etc/keepalived/keepalived.conf (Backup)

global_defs {
    router_id LVS_BACKUP
}

vrrp_script check_nginx {
    script "/etc/keepalived/check_nginx.sh"
    interval 2
    weight -20
    fall 3
    rise 2
}

vrrp_instance VI_1 {
    state BACKUP
    interface eth0
    virtual_router_id 51
    priority 90
    advert_int 1
    
    authentication {
        auth_type PASS
        auth_pass MySecretKey
    }
    
    virtual_ipaddress {
        192.168.1.200/24 dev eth0
    }
    
    track_script {
        check_nginx
    }
}

5.5 健康检查脚本

#!/bin/bash
# /etc/keepalived/check_nginx.sh

if ! pidof nginx > /dev/null 2>&1; then
    systemctl start nginx
    sleep 2
    if ! pidof nginx > /dev/null 2>&1; then
        exit 1
    fi
fi
exit 0

5.6 状态通知脚本

#!/bin/bash
# /etc/keepalived/notify.sh

STATE=$1
HOSTNAME=$(hostname)
DATE=$(date '+%Y-%m-%d %H:%M:%S')

case $STATE in
    master)
        echo "$DATE - $HOSTNAME became MASTER" >> /var/log/keepalived-state.log
        # 发送告警通知
        ;;
    backup)
        echo "$DATE - $HOSTNAME became BACKUP" >> /var/log/keepalived-state.log
        ;;
    fault)
        echo "$DATE - $HOSTNAME entered FAULT state" >> /var/log/keepalived-state.log
        # 发送紧急告警
        ;;
esac

5.7 脑裂问题与防护

脑裂是指 Master 和 Backup 同时持有 VIP,导致网络冲突。

防护措施:

# 检测脚本:发现脑裂时自动降级
#!/bin/bash
# /etc/keepalived/check_split_brain.sh

VIP="192.168.1.200"
LOCAL_IP=$(hostname -I | awk '{print $1}')
PEER_IP="192.168.1.2"

# 检查对端是否在线
if ping -c 1 -W 1 $PEER_IP > /dev/null 2>&1; then
    # 对端在线,检查 VIP 冲突
    ARP_COUNT=$(arping -c 1 -I eth0 $VIP 2>/dev/null | grep -c "reply")
    if [ "$ARP_COUNT" -gt 1 ]; then
        echo "$(date) - Split brain detected! Stopping keepalived" >> /var/log/keepalived-sb.log
        systemctl stop keepalived
        exit 1
    fi
fi
exit 0

其他防护手段:

  • 使用独立的心跳线(非业务网络)

  • 配置 unicast_src_ipunicast_peer 单播通信

  • 设置合理的 advert_intweight

# 单播配置(避免组播被交换机过滤)
vrrp_instance VI_1 {
    unicast_src_ip 192.168.1.10
    unicast_peer {
        192.168.1.11
    }
}

六、云负载均衡

6.1 阿里云 SLB(Server Load Balancer)

四层/七层负载均衡,支持 TCP、UDP、HTTP、HTTPS。

# 使用阿里云 CLI 创建 SLB 实例
aliyun slb CreateLoadBalancer \
    --RegionId cn-hangzhou \
    --LoadBalancerName prod-web-slb \
    --AddressType internet \
    --InternetChargeType paybytraffic

# 添加后端服务器
aliyun slb AddBackendServers \
    --LoadBalancerId lb-xxxxx \
    --BackendServers '[{"ServerId":"i-xxx1","Weight":"100"},{"ServerId":"i-xxx2","Weight":"100"}]'

# 配置健康检查
aliyun slb SetHealthCheck \
    --LoadBalancerId lb-xxxxx \
    --ListenerPort 80 \
    --HealthCheck on \
    --HealthyThreshold 3 \
    --UnhealthyThreshold 3 \
    --HealthCheckInterval 2 \
    --HealthCheckURI /health \
    --HealthCheckConnectPort 80

6.2 阿里云 ALB(Application Load Balancer)

七层应用型负载均衡,支持高级路由、WebSocket、gRPC。

# 创建 ALB 实例
aliyun alb CreateLoadBalancer \
    --LoadBalancerName prod-app-alb \
    --AddressType Internet \
    --VpcId vpc-xxxxx \
    --ZoneId '[{"ZoneId":"cn-hangzhou-h","VSwitchId":"vsw-xxx1"},{"ZoneId":"cn-hangzhou-g","VSwitchId":"vsw-xxx2"}]'

6.3 云负载均衡对比

产品

层级

协议支持

适用场景

SLB(CLB)

四层/七层

TCP/UDP/HTTP/HTTPS

通用 Web 应用

ALB

七层

HTTP/HTTPS/gRPC/WebSocket

微服务、高级路由

NLB

四层

TCP/UDP/TLS

高性能、超大并发

GWLB

三层/四层

IP

安全设备链

6.4 华为云 ELB

# 创建弹性负载均衡器
hcloud elb loadbalancer create \
    --name prod-elb \
    --vpc-id vpc-xxxxx \
    --type L4 \
    --availability-zones cn-north-4a cn-north-4b

6.5 AWS ELB

# 创建 Application Load Balancer
aws elbv2 create-load-balancer \
    --name prod-alb \
    --type application \
    --subnets subnet-xxx1 subnet-xxx2 \
    --security-groups sg-xxxxx

# 创建目标组
aws elbv2 create-target-group \
    --name web-targets \
    --protocol HTTP \
    --port 80 \
    --vpc-id vpc-xxxxx \
    --health-check-path /health \
    --health-check-interval-seconds 10 \
    --healthy-threshold-count 3 \
    --unhealthy-threshold-count 3

七、高可用架构设计

7.1 主备模式(Active-Standby)

┌─────────────┐     ┌─────────────┐
│   Master     │     │   Backup     │
│  (Active)    │◄───►│  (Standby)   │
│  192.168.1.10│     │ 192.168.1.11 │
└──────┬───────┘     └──────┬───────┘
       │                    │
       └──── VIP: 192.168.1.200 ────┘
                   │
              ┌────┴────┐
              │  Client  │
              └─────────┘

优点:简单、故障切换快。缺点:资源利用率低(备机闲置)。

7.2 双主模式(Active-Active)

         ┌──────────────────┐
         │   DNS 轮询 / LB   │
         └───┬──────────┬───┘
             │          │
    ┌────────▼──┐  ┌────▼────────┐
    │  Node A    │  │  Node B     │
    │  (Active)  │  │  (Active)   │
    │ 192.168.1.10│ │ 192.168.1.11│
    └────────┬───┘  └────┬────────┘
             │           │
             └─────┬─────┘
                   │
            ┌──────▼──────┐
            │  共享存储/DB  │
            └─────────────┘

优点:资源充分利用。缺点:需处理数据一致性。

7.3 集群模式(Cluster)

              ┌─────────────┐
              │  负载均衡器   │
              └──┬───┬───┬──┘
                 │   │   │
          ┌──────┘   │   └──────┐
          ▼          ▼          ▼
     ┌─────────┐ ┌─────────┐ ┌─────────┐
     │ Node 1  │ │ Node 2  │ │ Node 3  │
     └────┬────┘ └────┬────┘ └────┬────┘
          │           │           │
          └───────────┼───────────┘
                      ▼
              ┌──────────────┐
              │  数据库集群    │
              └──────────────┘

7.4 多活架构(Multi-Active)

  ┌──────────────┐              ┌──────────────┐
  │   机房 A      │              │   机房 B      │
  │              │              │              │
  │ ┌────┐┌────┐│   数据同步   │ ┌────┐┌────┐│
  │ │Web1││Web2││◄────────────►│ │Web1││Web2││
  │ └──┬─┘└──┬─┘│              │ └──┬─┘└──┬─┘│
  │    └──┬──┘  │              │    └──┬──┘  │
  │   ┌───▼───┐ │              │   ┌───▼───┐ │
  │   │DB-M   │ │◄────────────►│   │DB-M   │ │
  │   └───────┘ │              │   └───────┘ │
  └──────────────┘              └──────────────┘
         ▲                            ▲
         └──────────┬─────────────────┘
              ┌─────▼─────┐
              │ 全局 DNS / │
              │ GSLB      │
              └───────────┘

八、故障转移策略

8.1 自动故障转移流程

故障检测 → 故障确认 → 流量切换 → 服务恢复 → 流量回切
   │           │          │          │          │
  健康检查   多次确认    VIP漂移    自愈/重启   人工确认

8.2 故障检测配置示例

# Keepalived 健康检查 + 自动故障转移
# 结合 Nginx 和 Keepalived

# 1. Nginx 健康检查端点
# nginx.conf
location /health {
    access_log off;
    return 200 'OK';
    add_header Content-Type text/plain;
}

# 2. 后端服务健康检查
upstream backend {
    server 192.168.1.101:8080 max_fails=3 fail_timeout=30s;
    server 192.168.1.102:8080 max_fails=3 fail_timeout=30s;
}

# 3. Keepalived 检查 Nginx 存活
vrrp_script check_nginx {
    script "curl -s -o /dev/null -w '%{http_code}' http://localhost/health | grep -q 200"
    interval 3
    weight -20
    fall 3
    rise 2
}

8.3 数据库故障转移

# MySQL 主从自动切换(MHA 方案)
# 检查主库状态
masterha_check_repl --conf=/etc/mha/app1.cnf

# 启动 MHA Manager
masterha_manager --conf=/etc/mha/app1.cnf \
    --remove_dead_master_conf \
    --ignore_last_failover

# 手动切换
masterha_master_switch --master_state=dead \
    --conf=/etc/mha/app1.cnf \
    --dead_master_host=192.168.1.100 \
    --new_master_host=192.168.1.101

九、负载均衡监控

9.1 HAProxy 监控

# 通过 Socket 获取统计信息
echo "show stat" | socat /var/run/haproxy.sock stdio

# 通过 stats 页面采集指标(Prometheus)
# haproxy_exporter 配置
cat > /etc/systemd/system/haproxy_exporter.service << 'EOF'
[Unit]
Description=HAProxy Exporter
After=network.target

[Service]
ExecStart=/usr/local/bin/haproxy_exporter \
    --haproxy.scrape-uri=http://localhost:8404/stats;csv
Restart=always

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl start haproxy_exporter

9.2 Nginx 监控

# 启用 stub_status
location /nginx_status {
    stub_status;
    allow 127.0.0.1;
    allow 10.0.0.0/8;
    deny all;
}

# 使用 nginx-prometheus-exporter
nginx-prometheus-exporter \
    -nginx.scrape-uri=http://localhost/nginx_status

9.3 Prometheus 告警规则

# /etc/prometheus/rules/load_balancer.yml
groups:
  - name: load_balancer_alerts
    rules:
      - alert: HAProxyBackendDown
        expr: haproxy_backend_active_servers == 0
        for: 1m
        labels:
          severity: critical
        annotations:
          summary: "HAProxy backend {{ $labels.backend }} has no active servers"

      - alert: HAProxyHighErrorRate
        expr: rate(haproxy_backend_http_responses_total{code="5xx"}[5m]) > 0.1
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "High 5xx error rate on {{ $labels.backend }}"

      - alert: NginxHighConnections
        expr: nginx_connections_active > 1000
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "Nginx active connections exceed 1000"

      - alert: KeepalivedVIPFlapping
        expr: changes(keepalived_state[5m]) > 3
        for: 1m
        labels:
          severity: critical
        annotations:
          summary: "VIP flapping detected on {{ $labels.instance }}"

9.4 Grafana Dashboard 关键指标

  • 连接数:当前活跃连接、每秒新建连接

  • 吞吐量:请求/秒、字节入/出

  • 健康状态:后端服务器 UP/DOWN 数量

  • 响应时间:后端平均响应时间、P99 延迟

  • 错误率:5xx/4xx 比例

  • VIP 状态:当前 Master 节点、状态切换次数


十、完整高可用架构部署方案

10.1 架构总览

                    ┌─────────────┐
                    │   客户端     │
                    └──────┬──────┘
                           │
                    ┌──────▼──────┐
                    │  DNS / GSLB  │
                    └──────┬──────┘
                           │
          ┌────────────────┼────────────────┐
          │                                  │
   ┌──────▼──────┐                   ┌──────▼──────┐
   │   LB-Master  │                   │   LB-Backup  │
   │ (HAProxy +   │◄─────VRRP───────►│ (HAProxy +   │
   │  Keepalived) │                   │  Keepalived) │
   │  VIP: .200   │                   │              │
   └──────┬──────┘                   └──────┬──────┘
          │                                  │
   ┌──────┼──────────┬───────────────┬──────┘
   │      │          │               │
┌──▼──┐┌──▼──┐ ┌────▼────┐   ┌─────▼───┐
│Web1 ││Web2 │ │ Web3    │   │ Web4    │
└──┬──┘└──┬──┘ └────┬────┘   └────┬────┘
   │      │         │              │
   └──────┼─────────┼──────────────┘
          │         │
   ┌──────▼─────────▼──────┐
   │    数据库集群           │
   │  MySQL Master-Slave    │
   │  / Redis Sentinel      │
   └────────────────────────┘

10.2 部署步骤

第一步:部署负载均衡层

# LB Master 节点
# 安装 HAProxy
yum install -y haproxy keepalived

# 配置 HAProxy(参考第三节配置)
cp haproxy.cfg /etc/haproxy/haproxy.cfg
systemctl enable haproxy
systemctl start haproxy

# 配置 Keepalived(Master 节点)
cat > /etc/keepalived/keepalived.conf << 'EOF'
global_defs {
    router_id LB_MASTER
}

vrrp_script check_haproxy {
    script "killall -0 haproxy"
    interval 2
    weight -20
    fall 3
    rise 2
}

vrrp_instance VI_WEB {
    state MASTER
    interface eth0
    virtual_router_id 51
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass HA_Secret
    }
    virtual_ipaddress {
        192.168.1.200/24
    }
    track_script {
        check_haproxy
    }
}
EOF

systemctl enable keepalived
systemctl start keepalived

第二步:部署应用服务器

# 所有 Web 节点通用配置
# 安装 Nginx
yum install -y nginx

# 配置 Nginx 反向代理
cat > /etc/nginx/conf.d/app.conf << 'EOF'
upstream app_backend {
    server 127.0.0.1:8080;
}

server {
    listen 80;
    location / {
        proxy_pass http://app_backend;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
    location /health {
        access_log off;
        return 200 'OK';
    }
}
EOF

systemctl enable nginx
systemctl start nginx

第三步:配置数据库高可用

# MySQL 主从复制配置(Master)
cat >> /etc/my.cnf << 'EOF'
[mysqld]
server-id = 1
log_bin = mysql-bin
binlog_format = ROW
sync_binlog = 1
innodb_flush_log_at_trx_commit = 1
EOF

# 创建复制用户
mysql -e "CREATE USER 'repl'@'%' IDENTIFIED BY 'ReplPass123';"
mysql -e "GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%';"

# Slave 节点配置
mysql -e "CHANGE MASTER TO \
    MASTER_HOST='192.168.1.201', \
    MASTER_USER='repl', \
    MASTER_PASSWORD='ReplPass123', \
    MASTER_AUTO_POSITION=1;"
mysql -e "START SLAVE;"

第四步:配置监控告警

# Prometheus 抓取配置
cat >> /etc/prometheus/prometheus.yml << 'EOF'
scrape_configs:
  - job_name: 'haproxy'
    static_configs:
      - targets: ['192.168.1.10:9101', '192.168.1.11:9101']

  - job_name: 'nginx'
    static_configs:
      - targets: ['192.168.1.101:9113', '192.168.1.102:9113']

  - job_name: 'node'
    static_configs:
      - targets:
        - '192.168.1.10:9100'
        - '192.168.1.11:9100'
        - '192.168.1.101:9100'
        - '192.168.1.102:9100'
EOF

systemctl reload prometheus

10.3 故障演练清单

# 1. 模拟 Web 服务器宕机
systemctl stop nginx    # 在 Web1 上执行
# 预期:LB 自动摘除 Web1,流量转移到 Web2

# 2. 模拟 LB Master 故障
systemctl stop keepalived    # 在 Master 上执行
# 预期:VIP 漂移到 Backup,业务无感知

# 3. 模拟数据库主库故障
systemctl stop mysql    # 在 DB Master 上执行
# 预期:MHA 自动提升 Slave 为新 Master

# 4. 模拟网络分区
iptables -A INPUT -s 192.168.1.11 -j DROP    # Master 上执行
# 预期:检测脑裂防护是否生效

# 验证命令
ip addr show eth0 | grep 192.168.1.200    # 检查 VIP
curl -I http://192.168.1.200/             # 检查服务可用性

10.4 运维检查清单

检查项

频率

命令/方法

VIP 状态

每日

ip addr show eth0

HAProxy 后端状态

每日

echo "show stat" | socat stdio

Keepalived 日志

每日

journalctl -u keepalived --since today

数据库复制状态

每日

SHOW SLAVE STATUS

证书有效期

每周

openssl x509 -enddate -noout -in cert.pem

故障演练

每季度

按演练清单执行

配置备份

每次变更

版本控制 + 异地备份


总结

组件

层级

特点

推荐场景

LVS

四层

内核态,性能极高

大流量入口

HAProxy

四层/七层

功能丰富,ACL 强大

HTTP 七层代理

Nginx

七层

Web 服务器 + 代理

Web 应用入口

Keepalived

三层

VIP 漂移,消除 LB 单点

LB 高可用

云 SLB/ALB

四层/七层

免运维,弹性伸缩

云上业务

高可用架构的核心原则:消除单点故障、自动故障检测、快速故障转移、定期故障演练。没有 100% 的可用性,但通过合理的架构设计,可以将故障影响降到最低。