# 3、负载均衡的高可用方案

### 为什么要采用双机热备？

单节点Haproxy不具备高可用，必须要有冗余设计

![](/files/-LfnTJprRWI7yzCZRgOh)

## 利用Keepalived实现双机热备方案

原理：虚拟出来一个虚拟IP,keepalived去争抢，谁争抢到谁就是主服务器。

![](/files/-LfnTJptJZ2OKWL-y0Ie)

具体方案架构：

![](/files/-LfnTJpv6146Pj9bNu1b)182.18.0.15是Docker内的虚拟IP不能被外网使用，所以需要借助宿主机器上安装keepalived，把192.168.99.65可以被外网访问的这个ip映射到Docker这个虚拟ip182.18 .0.15。

当应用程序访问192.168.99.65发送数据库请求，这个请求就会路由到docker的这个虚拟ip（182.18 .0.15）上，然后转发到主服务器容器，再负载均衡到PXC集群的某个mysql数据库。

## 安装Keepalived

keepalived必须要安装在Haproxy所在的容器之内。

```
# 进入到后台运行haproxy1的docker容器
$ docker exec -it haproxy1 bash
$ apt-get update
$ apt-get install keepalived
```

> 建议apt-get加速，比如设置成163镜像

## Keepalived 配置文件

Keepalived的配置文件是`/etc/Keepalived/Keepalived.conf`

**修改配置文件**

方式1：可以在容器内修改

```
$ apt-get install vim
$ vim /etc/keepalived/keepalived.conf
```

方式2：宿主机上定义好，传入到容器中

配置文件说明：

```
vrrp_instance  VI_1 {
    state  MASTER
    interface  eth0
    virtual_router_id  51
    priority  100
    advert_int  1
    authentication {
        auth_type  PASS
        auth_pass  123456
    }
    virtual_ipaddress {
        172.18.0.15
    }
}
```

**state MASER:** 标识Keepalived的身份（Master 主服务器，BACKUP备用服务器）。主服务器要抢占虚拟IP,备用服器不会抢占IP。

如果把每个Keepalived的配置文件都定义成身份是MASTER,这些节点启动之后都会去争抢虚拟IP，只会有一个节点抢到，其他节点身份自动降级为SLAVE。

**interface eth0：**&#x865A;拟ip保存到**eth0**网卡，宿主机可以访问，局域网其他电脑是看不到这个**eth0**网卡，所以需要在宿主机上把**eth0这个**网卡里的虚拟IP映射到局域网上的某一个虚拟ip上，所以后续还在宿主机上安装Keepalived。

**virtual\_router\_id 51：**&#x865A;拟路由标识，MASTER和BACKUP的虚拟路由标识必须一致。标识可以 0\~255.

**priority 100：**&#x4D;ASTER权重要高于BACKUP，数字越大优选级越高。

**advert\_int 1：**&#x4B;eepalived节点之间同步检查的实际间隔，单位为秒，主备之间必须一致。

**authentication：**&#x4B;eepalived节点之间通信需要验证，主从服务器验证方式。主备必须使用相同 密码爱能正常通信。

**virtual\_ipaddress：**&#x865A;拟IP地址.可以设置多个虚拟IP地址，每行一个。注意和你的PXC集群同网段.

## 启动Keepalived

haproxy1容器中启动Keepalived

```
$ service keepalived start
```

宿主机器上ping 一下虚拟IP测试

```
$ ping 172.18.0.15
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docker.shujuwajue.com/mysql-ji-qun/pxcji-qun/fu-zai-jun-heng-de-gao-ke-yong-fang-an.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
