---
title: "利用keepalived构建高可用MySQL-HA(转)"
author: "zhb8015"
date: "2014-06-25T14:50:42Z"
tags: []
categories: ["数据库"]
slug: "keepalived-mysql-ha"
draft: false
lastmod: "2014-06-25T14:50:42Z"
id: 2084913
url: "https://peter8015.iteye.com/blog/2084913"
---

关于MySQL-HA，目前有多种解决方案，比如heartbeat、drbd、mmm、共享存储，但是它们各有优缺点。heartbeat、drbd配置较为复杂，需要自己写脚本才能实现MySQL自动切换，对于不会脚本语言的人来说，这无疑是一种脑裂问题；对于mmm，生产环境中很少有人用，且mmm 管理端需要单独运行一台服务器上，要是想实现高可用，就得对mmm管理端做HA，这样无疑又增加了硬件开支；对于共享存储，个人觉得MySQL数据还是放在本地较为安全，存储设备毕竟存在单点隐患。使用MySQL双master+keepalived是一种非常好的解决方案，在MySQL-HA环境中，MySQL互为主从关系，这样就保证了两台MySQL数据的一致性，然后用keepalived实现虚拟IP，通过keepalived自带的服务监控功能来实现MySQL故障时自动切换。

下面，我把即将上线的一个生产环境中的架构与大家分享一下，看一下这个架构中，MySQL-HA是如何实现的，环境拓扑如下

1. MySQL-VIP：192.168.1.200
2. MySQL-master1：192.168.1.201
3. MySQL-master2：192.168.1.202
4. OS版本：CentOS 5.4
5. MySQL版本：5.0.89
6. Keepalived版本：1.1.20

**一、MySQL master-master配置**

1、修改MySQL配置文件

两台MySQL均如要开启binlog日志功能，开启方法：在MySQL配置文件\[MySQLd]段中加上log-bin=MySQL-bin选项

两台MySQL的server-ID不能一样，默认情况下两台MySQL的serverID都是1，需将其中一台修改为2即可

2、将192.168.1.201设为192.168.1.202的主服务器

在192.168.1.201上新建授权用户

1. MySQL&gt; grant replication slave on \*.* to 'replication'@'%' identified by 'replication';
2. Query OK, 0 rows affected (0.00 sec)
3. MySQL&gt; show master status;
4. +------------------+----------+--------------+------------------+
5. | File             | Position | Binlog\_Do\_DB | Binlog\_Ignore\_DB |
6. +------------------+----------+--------------+------------------+
7. | MySQL-bin.000003 |      374 |              |                  |
8. +------------------+----------+--------------+------------------+
9. 1 row in set (0.00 sec)

在192.168.1.202上将192.168.1.201设为自己的主服务器

01. MySQL&gt; change master to master\_host='192.168.1.201',master\_user='replication',master\_password='replication',master\_log\_file='MySQL-bin.000003',master\_log\_pos=374;
02. Query OK, 0 rows affected (0.05 sec)
03. MySQL&gt; start slave;
04. Query OK, 0 rows affected (0.00 sec)
05. MySQL&gt; show slave status\\G
06. \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\** 1. row \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\**
07. Slave\_IO\_State: Waiting for master to send event
08. Master\_Host: 192.168.1.201
09. Master\_User: replication
10. Master\_Port: 3306
11. Connect\_Retry: 60
12. Master\_Log\_File: MySQL-bin.000003
13. Read\_Master\_Log\_Pos: 374
14. Relay\_Log\_File: MySQL-master2-relay-bin.000002
15. Relay\_Log\_Pos: 235
16. Relay\_Master\_Log\_File: MySQL-bin.000003
17. Slave\_IO\_Running: Yes
18. Slave\_SQL\_Running: Yes
19. Replicate\_Do\_DB:
20. Replicate\_Ignore\_DB:
21. Replicate\_Do\_Table:
22. Replicate\_Ignore\_Table:
23. Replicate\_Wild\_Do\_Table:
24. Replicate\_Wild\_Ignore\_Table:
25. Last\_Errno: 0
26. Last\_Error:
27. Skip\_Counter: 0
28. Exec\_Master\_Log\_Pos: 374
29. Relay\_Log\_Space: 235
30. Until\_Condition: None
31. Until\_Log\_File:
32. Until\_Log\_Pos: 0
33. Master\_SSL\_Allowed: No
34. Master\_SSL\_CA\_File:
35. Master\_SSL\_CA\_Path:
36. Master\_SSL\_Cert:
37. Master\_SSL\_Cipher:
38. Master\_SSL\_Key:
39. Seconds\_Behind\_Master: 0
40. 1 row in set (0.00 sec)

3、将192.168.1.202设为192.168.1.201的主服务器

在192.168.1.202上新建授权用户

1. MySQL&gt; grant replication slave on \*.* to 'replication'@'%' identified by 'replication';
2. Query OK, 0 rows affected (0.00 sec)
3. MySQL&gt; show master status;
4. +------------------+----------+--------------+------------------+
5. | File             | Position | Binlog\_Do\_DB | Binlog\_Ignore\_DB |
6. +------------------+----------+--------------+------------------+
7. | MySQL-bin.000003 |      374 |              |                  |
8. +------------------+----------+--------------+------------------+
9. 1 row in set (0.00 sec)

在192.168.1.201上，将192.168.1.202设为自己的主服务器

01. MySQL&gt; change master to master\_host='192.168.1.202',master\_user='replication',master\_password='replication',master\_log\_file='MySQL-bin.000003',master\_log\_pos=374;
02. Query OK, 0 rows affected (0.05 sec)
03. MySQL&gt; start slave;
04. Query OK, 0 rows affected (0.00 sec)
05. MySQL&gt; show slave status\\G
06. \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\** 1. row \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\**
07. Slave\_IO\_State: Waiting for master to send event
08. Master\_Host: 192.168.1.202
09. Master\_User: replication
10. Master\_Port: 3306
11. Connect\_Retry: 60
12. Master\_Log\_File: MySQL-bin.000003
13. Read\_Master\_Log\_Pos: 374
14. Relay\_Log\_File: MySQL-master1-relay-bin.000002
15. Relay\_Log\_Pos: 235
16. Relay\_Master\_Log\_File: MySQL-bin.000003
17. Slave\_IO\_Running: Yes
18. Slave\_SQL\_Running: Yes
19. Replicate\_Do\_DB:
20. Replicate\_Ignore\_DB:
21. Replicate\_Do\_Table:
22. Replicate\_Ignore\_Table:
23. Replicate\_Wild\_Do\_Table:
24. Replicate\_Wild\_Ignore\_Table:
25. Last\_Errno: 0
26. Last\_Error:
27. Skip\_Counter: 0
28. Exec\_Master\_Log\_Pos: 374
29. Relay\_Log\_Space: 235
30. Until\_Condition: None
31. Until\_Log\_File:
32. Until\_Log\_Pos: 0
33. Master\_SSL\_Allowed: No
34. Master\_SSL\_CA\_File:
35. Master\_SSL\_CA\_Path:
36. Master\_SSL\_Cert:
37. Master\_SSL\_Cipher:
38. Master\_SSL\_Key:
39. Seconds\_Behind\_Master: 0
40. 1 row in set (0.00 sec)

4、MySQL同步测试

如上述均正确配置，现在任何一台MySQL上更新数据都会同步到另一台MySQL，MySQL同步在此不再演示

**二、keepalived安装及配置**

1、192.168.1.201服务器上keepalived安装及配置

安装keepalived

1. #tar zxvf keepalived-1.1.20.tar.gz
2. #cd keepalived-1.1.20
3. #./configure --prefix=/usr/local/keepalived --with-kernel-dir=/usr/src/kernels/2.6.18-164.el5-i686
4. #make && make install

配置keepalived

我们自己在新建一个配置文件，默认情况下keepalived启动时会去/etc/keepalived目录下找配置文件

01. #mkdir /etc/keepalived
02. #vi /etc/keepalived/keepalived.conf
03. ! Configuration File for keepalived
04. global\_defs {
05. notification\_email {
06. luwenju@live.cn
07. }
08. notification\_email\_from luwenju@live.cn
09. smtp\_server 127.0.0.1
10. smtp\_connect\_timeout 30
11. router\_id MySQL-ha
12. }
13. vrrp\_instance VI\_1 {
14. state BACKUP   #两台配置此处均是BACKUP
15. interface eth0
16. virtual\_router\_id 51
17. priority 100   #优先级，另一台改为90
18. advert\_int 1
19. nopreempt  #不抢占，只在优先级高的机器上设置即可，优先级低的机器不设置
20. authentication {
21. auth\_type PASS
22. auth\_pass 1111
23. }
24. virtual\_ipaddress {
25. 192.168.1.200
26. }
27. }
28. virtual\_server 192.168.1.200 3306 {
29. delay\_loop 2   #每个2秒检查一次real\_server状态
30. lb\_algo wrr   #LVS算法
31. lb\_kind DR    #LVS模式
32. persistence\_timeout 60   #会话保持时间
33. protocol TCP
34. real\_server 192.168.1.201 3306 {
35. weight 3
36. notify\_down /usr/local/MySQL/bin/MySQL.sh  #检测到服务down后执行的脚本
37. TCP\_CHECK {
38. connect\_timeout 10    #连接超时时间
39. nb\_get\_retry 3       #重连次数
40. delay\_before\_retry 3   #重连间隔时间
41. connect\_port 3306   #健康检查端口
42. }
43. }

编写检测服务down后所要执行的脚本

1. #vi /usr/local/MySQL/bin/MySQL.sh
2. #!/bin/sh
3. pkill keepalived
4. #chmod +x /usr/local/MySQL/bin/MySQL.sh

注：此脚本是上面配置文件notify\_down选项所用到的，keepalived使用notify\_down选项来检查real\_server的服务状态，当发现real\_server服务故障时，便触发此脚本；我们可以看到，脚本就一个命令，通过pkill keepalived强制杀死keepalived进程，从而实现了MySQL故障自动转移。另外，我们不用担心两个MySQL会同时提供数据更新操作，因为每台MySQL上的keepalived的配置里面只有本机MySQL的IP+VIP，而不是两台MySQL的IP+VIP

启动keepalived

1. #/usr/local/keepalived/sbin/keepalived –D
2. #ps -aux | grep keepalived

**测试**

找一台局域网PC，然后去ping  MySQL的VIP，这时候MySQL的VIP是可以ping的通的

停止MySQL服务，看keepalived健康检查程序是否会触发我们编写的脚本

2、192.168.1.202上keepalived安装及配置

安装keepalived

1. #tar zxvf keepalived-1.1.20.tar.gz
2. #cd keepalived-1.1.20
3. #./configure --prefix=/usr/local/keepalived --with-kernel-dir=/usr/src/kernels/2.6.18-164.el5-i686
4. #make && make install

配置keepalived

这台配置和上面基本一样，但有三个地方不同：优先级为90、无抢占设置、real\_server为本机IP

01. #mkdir /etc/keepalived
02. #vi /etc/keepalived/keepalived.conf
03. ! Configuration File for keepalived
04. global\_defs {
05. notification\_email {
06. luwenju@live.cn
07. }
08. notification\_email\_from luwenju@live.cn
09. smtp\_server 127.0.0.1
10. smtp\_connect\_timeout 30
11. router\_id MySQL-ha
12. }
13. vrrp\_instance VI\_1 {
14. state BACKUP
15. interface eth0
16. virtual\_router\_id 51
17. priority 90
18. advert\_int 1
19. authentication {
20. auth\_type PASS
21. auth\_pass 1111
22. }
23. virtual\_ipaddress {
24. 192.168.1.200
25. }
26. }
27. virtual\_server 192.168.1.200 3306 {
28. delay\_loop 2
29. lb\_algo wrr
30. lb\_kind DR
31. persistence\_timeout 60
32. protocol TCP
33. real\_server 192.168.1.202 3306 {
34. weight 3
35. notify\_down /usr/local/MySQL/bin/MySQL.sh
36. TCP\_CHECK {
37. connect\_timeout 10
38. nb\_get\_retry 3
39. delay\_before\_retry 3
40. connect\_port 3306
41. }
42. }

编写检测服务down后所要执行的脚本

1. #vi /usr/local/MySQL/bin/MySQL.sh
2. #!/bin/sh
3. pkill keepalived
4. #chmod +x /usr/local/MySQL/bin/MySQL.sh
5. 启动keepalived
6. #/usr/local/keepalived/sbin/keepalived –D
7. #ps -aux | grep keepalived

测试

停止MySQL服务，看keepalived健康检查程序是否会触发我们编写的脚本

**三、测试**

MySQL远程登录测试

我们找一台安装有MySQL客户端的windows，然后登录VIP，看是否能登录，在登录之两台MySQL服务器都要授权允许从远程登录

1. MySQL&gt; grant all privileges on \*.* to 'root'@'%' identified by '123456';
2. Query OK, 0 rows affected (0.00 sec)
3. MySQL&gt; flush privileges;
4. Query OK, 0 rows affected (0.00 sec)

使用客户端登录VIP测试

1. C:\\MySQL\\bin&gt;MySQL.exe -uroot -p123456 -h192.168.1.200 -P3306
2. Welcome to the MySQL monitor.  Commands end with ; or \\g.
3. Your MySQL connection id is 224
4. Server version: 5.0.89-log Source distribution
5. Type 'help;' or '\\h' for help. Type '\\c' to clear the current input statement.
6. MySQL&gt;

● keepalived故障转移测试

※在windows客户端一直去ping  VIP，然后关闭192.168.1.201上的keepalived，正常情况下VIP就会切换到192.168.1.202上面去

※开启192.168.1.201上的keepalived，关闭192.168.1.202上的keepalived，看是否能自动切换，正常情况下VIP又会属于192.168.1.201

注：keepalived切换速度还是非常块的，整个切换过程只需1-3秒

● MySQL故障转移测试

※在192.168.1.201上关闭MySQL服务，看VIP是否会切换到192.168.1.202上

※开启192.168.1.201上的MySQL和keepalived，然后关闭192.168.1.202上的MySQL，看VIP是否会切换到192.168.1.201上

下面是用windows客户端连接的MySQL的VIP，在切换时我执行了一个MySQL查询命令，从执行show databases到显示出结果时间为3-5秒（大家可以看到上面有个错误提示，不过不用担心，因为我们的keepalived切换大概为3秒左右，这3秒左右VIP是谁都不属于的）

01. MySQL&gt; show databases;
02. ERROR 2006 (HY000): MySQL server has gone away
03. No connection. Trying to reconnect...
04. Connection id:    592
05. Current database: \*\** NONE \*\**
06. +--------------------+
07. | Database           |
08. +--------------------+
09. | information\_schema |
10. | MySQL              |
11. | test               |
12. +--------------------+
13. 3 rows in set (9.01 sec)

后话：世间万事万物，都不具备绝对的完美，就像上面的MySQL-HA一样，keepalived只能做到对3306的健康检查，但是做不到比如像MySQL复制中的slave-SQL、slave-IO进程的检查。所以要想做到一些细致的健康检查，还得需要借助额外的监控工具，比如nagios，然后用nagios实现短信、邮件报警，从而能够有效地解决问题。

【编辑推荐】

1. [MySQL数据库集群进行正确配置步骤](http://database.51cto.com/art/201006/204585.htm)
2. [MySQL 集群在Server1与Server2上如何安装MySQL](http://database.51cto.com/art/201005/200708.htm)
3. [MySQL集群配置](http://database.51cto.com/art/200512/15346.htm)
4. [MySQL集群自动安装脚本](http://database.51cto.com/art/200510/9926.htm)
5. [MySQL触发器如何正确使用](http://database.51cto.com/art/201005/200554.htm)