# 2、PXC 集群负载均衡

## 数据库负载均衡的必要性

虽然搭建了集群，但是不使用数据库负载均衡，单节点处理所有请求，负载高，性能差。

![](/files/-LfnTL56B4CTkOrQp7bV)

使用Haproxy 做负载均衡，请求被均匀分发给每个节点，单节点负载低，性能好。

![](/files/-LfnTL58UxDXpCf_9s14)

## 负载均衡中间件对比

![](/files/-LfnTL5A_C-bgRsZ2DT-)

lvs不支持虚拟机，所以在docker容器里安装是不可能的，haproxy一个经得起考验的负载均衡中间件。

## 安装Haproxy镜像

Docker仓库中保存了Haproxy的镜像，只需下载即可。

```
$ docker pull haproxy
```

下载了haproxy镜像后，不要着创建容器，因为haproxy镜像里是不包含配置文件的.

## 创建Haproxy配置文件

**宿主机上创建一个配置文件**

```
$ touch /home/soft/hapoxy/haproxy.cfg
```

配置文件目录可以自己去指定，可以采用目录映射技术把soft目录映射到haproxy容器里面。haproxy容器就可以找到这个配置文件；启动Haproxy的服务自然而然就有配置文件了。

> 配置文件详情可以参考：[Haproxy安装部署文档及多配置文件管理方案](https://zhangge.net/5125.html)

**创建Haproxy容器**

```
$ docker run -it -d -p 4001:8888 -p 4002:3306 -v /home/soft/hapoxy:/usr/local/etc/haproxy --name haproxy1 --privileged --net=net1 haproxy

# 进入到后台运行的docker容器
$ docker exec -it haproxy1 bash
$ haproxy -f /usr/local/etc/haproxy/haproxy.cfg
```

> 退出指令exit ,只是退出交互界面，不会停止容器运行。

-p 端口映射：8888端口是haproxy监控画面的端口，可以配置随意端口。

-v 目录映射

\--name 命名

进入到容器中指定haproxy的配置文件。

创建心跳检测MYSQL用户名(%表示任何ip都可以使用这个账号登录到mysql数据库，密码为空)

```
CREATE USER 'haproxy'@'%' IDENTIFIED BY '';
```


---

# 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/pxc-mysqlji-qun-fu-zai-jun-heng.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.
