centos7安装Keepalived2.0.8+MySQL5.7高可用 双主热备

1.环境准备

角色 主机ip 主机名 操作系统版本 安装软件及版本
VIP 192.168.31.220 虚拟地址
master1 192.168.31.130 master1 CentOS 7.5 mysql5.7.27+keepalived2.0.8
master2 192.168.31.131 master2 CentOS 7.5 mysql5.7.27+keepalived2.0.8

2. 离线安装mysql服务[100/101都执行]

首先,安装所需依赖:

yum -y install gcc-c++ pcre pcre-devel zlib zlib-devel openssl openssl-devel

关闭防火墙并禁止开机启动:

systemctl status firewalld
systemctl stop firewalld
systemctl disable firewalld
systemctl status firewalld

准备好mysql的离线安装文件:

MySql官网下载mysql-5.7.27-1.el7.x86_64.rpm-bundle,并复制到/opt/software/mysql文件夹中。

删除CentOS自带的MariaDB:

rpm -qa|grep mariadb

rpm -e --nodeps mariadb-libs

解压 mysql-5.7.27-1.el7.x86_64.rpm-bundle ,步骤:

cd mysql 
tar -xvf mysql-5.7.27-1.el7.x86_64.rpm-bundle.tar 

rpm命令安装:

cd /opt/software/mysql/mysql-5.7.27-1.el7.x86_64.rpm-bundle
rpm -ivh mysql-community-common-5.7.27-1.el7.x86_64.rpm

rpm -ivh mysql-community-libs-5.7.27-1.el7.x86_64.rpm

rpm -ivh mysql-community-devel-5.7.27-1.el7.x86_64.rpm

rpm -ivh mysql-community-libs-compat-5.7.27-1.el7.x86_64.rpm

rpm -ivh mysql-community-client-5.7.27-1.el7.x86_64.rpm

rpm -ivh mysql-community-server-5.7.27-1.el7.x86_64.rpm

centos7安装Keepalived2.0.8+MySQL5.7高可用 双主热备_第1张图片

执行rpm -ivh mysql-community-server-5.7.27-1.el7.x86_64.rpm,出现错误,报错很简单,如错误信息显示,缺少net-tools.x86_64,libaio.x86_64,perl.x86_64三个依赖,使用yum安装即可。
1.查找依赖对应包

yum search perl
yum search libaio 
yum search net-tools

2.yum安装对应包

yum -y install perl.x86_64
yum -y install  libaio.x86_64
yum -y install net-tools.x86_64

centos7安装Keepalived2.0.8+MySQL5.7高可用 双主热备_第2张图片
再次执行 rpm -ivh mysql-community-server-5.7.27-1.el7.x86_64.rpm,安装成功!
当遇到安装失败时,看错误信息,然后去搜索一下对应的解决方案即可!

查看MySql运行状态:service mysqld status
在这里插入图片描述
启动MySql:systemctl start mysqld
centos7安装Keepalived2.0.8+MySQL5.7高可用 双主热备_第3张图片
查看root随机密码:

MySQL5.7会在安装后为root用户生成一个随机密码,而不是像以往版本的空密码。可以安全模式修改root登录密码或者用随机密码登录修改密码。下面用随机密码方式,MySQL为root用户生成的随机密码通过mysqld.log文件可以查找到:

grep 'temporary password' /var/log/mysqld.log   
mysql -u root -p

拿到密码 进行登录。
centos7安装Keepalived2.0.8+MySQL5.7高可用 双主热备_第4张图片
centos7安装Keepalived2.0.8+MySQL5.7高可用 双主热备_第5张图片
必须修改两个全局参数:
首先,修改validate_password_policy参数的值

set global validate_password_policy=0;

#修改密码的长度

set global validate_password_length=1;

#执行修改密码就可以了

ALTER USER 'root'@'localhost' IDENTIFIED BY 'root';

设置root可以远程登录:

mysql>GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'root' WITH GRANT OPTION;
mysql>flush privileges; 
mysql>exit;

重启MySql服务:

systemctl restart mysqld

用客户端进行连接,验证一下:
centos7安装Keepalived2.0.8+MySQL5.7高可用 双主热备_第6张图片

3. MySQL配置

在配置mysql之前要设置防火墙允许3306端口通过。

#关闭firewalld防火墙

systemctl stop firewalld

#从开机启动中移除

systemctl disable firewalld

1.master1 [192.168.31.130]的配置操:

vi /etc/my.cnf
#For advice on how to change settings please see
#http://dev.mysql.com/doc/refman/5.7/en/server-configuration-defaults.html
[mysqld]
datadir=/var/lib/mysql
#sock文件路径
socket=/var/lib/mysql/mysql.sock
#Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
#错误日志文件路径
log-error=/var/log/mysqld.log
#进程文件路径
pid-file=/var/run/mysqld/mysqld.pid
#mysql服务id
server-id=1
#二进制日志 存储数据发生改变的sql语句
log-bin=mysql-bin
#增量值得起点
auto-increment-offset=1
#每次增量间隔
auto-increment-increment=2 
#设置需要同步的数据库名称
#binlog_do_db=
exit
systemctl restart mysqld 

2.数据同步授权

set global validate_password_policy=0;
set global validate_password_length=1;
mysql> grant replication slave,replication client on *.* to root@'192.168.31.%' identified by "root";
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

最好将库锁住,仅仅允许读,以保证数据一致性;待主主同步环境部署后再解锁;
锁住后,就不能往表里写数据,但是重启mysql服务后就会自动解锁!
注意该参数设置后,如果自己同步对方数据,同步前一定要记得先解锁!

最好将库锁住,仅仅允许读,以保证数据一致性;待主主同步环境部署后再解锁;
锁住后,就不能往表里写数据,但是重启mysql服务后就会自动解锁!
注意该参数设置后,如果自己同步对方数据,同步前一定要记得先解锁
mysql> flush tables with read lock; 
Query OK, 0 rows affected (0.01 sec)

查看下log bin日志和pos值位置

mysql> show master status;

centos7安装Keepalived2.0.8+MySQL5.7高可用 双主热备_第7张图片

3.master2 [192.168.31.131] 的配置操:

 vi /etc/my.cnf
# For advice on how to change settings please see
# http://dev.mysql.com/doc/refman/5.7/en/server-configuration-defaults.html

[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
symbolic-links=0
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
server-id=2
log-bin=mysql-bin
auto-increment-offset=2
auto-increment-increment=2

#设置需要同步的数据库名称
#binlog_do_db=
exit
systemctl restart mysqld 

4.数据同步授权

set global validate_password_policy=0;
set global validate_password_length=1;
mysql> grant replication slave,replication client on *.* to root@'192.168.31.%' identified by "root";
Query OK, 0 rows affected, 1 warning (0.01 sec)
 mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
 mysql> flush tables with read lock; 
Query OK, 0 rows affected (0.01 sec)
 mysql> show master status;

centos7安装Keepalived2.0.8+MySQL5.7高可用 双主热备_第8张图片
5.master1做同步操作

先解锁步骤2中对master1的表解锁,为保持数据的一致性。

mysql> unlock tables;
Query OK, 0 rows affected (0.00 sec)
mysql> unlock tables;
Query OK, 0 rows affected (0.00 sec)
mysql> change  master to master_host='192.168.31.131',master_user='root',master_password='root',master_log_file='mysql-bin.000001',master_log_pos=787;
Query OK, 0 rows affected, 2 warnings (0.20 sec)
mysql> start slave;
Query OK, 0 rows affected (0.01 sec)
mysql> show slave status \G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.31.131
                  Master_User: root
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000004
          Read_Master_Log_Pos: 433
               Relay_Log_File: localhost-relay-bin.000015
                Relay_Log_Pos: 599
        Relay_Master_Log_File: mysql-bin.000004
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB: 
          Replicate_Ignore_DB: 
           Replicate_Do_Table: 
       Replicate_Ignore_Table: 
      Replicate_Wild_Do_Table: 
  Replicate_Wild_Ignore_Table: 
                   Last_Errno: 0
                   Last_Error: 
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 433
              Relay_Log_Space: 810
              Until_Condition: None
               Until_Log_File: 
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File: 
           Master_SSL_CA_Path: 
              Master_SSL_Cert: 
            Master_SSL_Cipher: 
               Master_SSL_Key: 
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error: 
               Last_SQL_Errno: 0
               Last_SQL_Error: 
  Replicate_Ignore_Server_Ids: 
             Master_Server_Id: 2
                  Master_UUID: 885049ec-8e9d-11ea-834f-000c291e0a7c
             Master_Info_File: /var/lib/mysql/master.info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
           Master_Retry_Count: 86400
                  Master_Bind: 
      Last_IO_Error_Timestamp: 
     Last_SQL_Error_Timestamp: 
               Master_SSL_Crl: 
           Master_SSL_Crlpath: 
           Retrieved_Gtid_Set: 
            Executed_Gtid_Set: 
                Auto_Position: 0
         Replicate_Rewrite_DB: 
                 Channel_Name: 
           Master_TLS_Version: 
1 row in set (0.00 sec)

6.master2做同步操作

先解锁步骤4中对master2的表的锁

mysql> unlock tables;
Query OK, 0 rows affected (0.00 sec)
mysql> unlock tables;
Query OK, 0 rows affected (0.00 sec)
mysql> change  master to master_host='192.168.31.130',master_user='root',master_password='root',master_log_file='mysql-bin.000001',master_log_pos=473;
Query OK, 0 rows affected, 2 warnings (0.20 sec)
mysql> start slave;
Query OK, 0 rows affected (0.01 sec)

mysql> show slave status \G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.31.130
                  Master_User: root
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000005
          Read_Master_Log_Pos: 154
               Relay_Log_File: localhost-relay-bin.000016
                Relay_Log_Pos: 367
        Relay_Master_Log_File: mysql-bin.000005
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB: 
          Replicate_Ignore_DB: 
           Replicate_Do_Table: 
       Replicate_Ignore_Table: 
      Replicate_Wild_Do_Table: 
  Replicate_Wild_Ignore_Table: 
                   Last_Errno: 0
                   Last_Error: 
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 154
              Relay_Log_Space: 744
              Until_Condition: None
               Until_Log_File: 
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File: 
           Master_SSL_CA_Path: 
              Master_SSL_Cert: 
            Master_SSL_Cipher: 
               Master_SSL_Key: 
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error: 
               Last_SQL_Errno: 0
               Last_SQL_Error: 
  Replicate_Ignore_Server_Ids: 
             Master_Server_Id: 1
                  Master_UUID: af6e48e7-8e99-11ea-be16-000c298641f0
             Master_Info_File: /var/lib/mysql/master.info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
           Master_Retry_Count: 86400
                  Master_Bind: 
      Last_IO_Error_Timestamp: 
     Last_SQL_Error_Timestamp: 
               Master_SSL_Crl: 
           Master_SSL_Crlpath: 
           Retrieved_Gtid_Set: 
            Executed_Gtid_Set: 
                Auto_Position: 0
         Replicate_Rewrite_DB: 
                 Channel_Name: 
           Master_TLS_Version: 
1 row in set (0.00 sec)

4.Keepalived的安装配置

1.将压缩包tar zxvf keepalived-2.0.18.tar.gz 传到 /usr/mysql下【两台机器都执行】:

tar -zxvf keepalived-2.0.18.tar.gz
cd keepalived-2.0.18/
yum install -y openssl-devel libnl-devel libnl3-devel libnfnetlink-devel
yum groupinstall  -y "Development Tools"
./configure --prefix=/usr/local/keepalived

出现这样,即为成功,可向下执行:
centos7安装Keepalived2.0.8+MySQL5.7高可用 双主热备_第9张图片

make && make install

2.修改master1【192.168.31.130】的配置文件

vi /etc/keepalived/keepalived.conf
! Configuration File for keepalived 
global_defs {
    notification_email {                #关于邮件的设置
          [email protected]             #email send to
    }
 
    notification_email_from [email protected]
        smtp_server 127.0.0.1 
        smtp_connect_timeout 30
        router_id MASTER-HA
}
 
vrrp_script chk_mysql_port {            #检测mysql服务是否在运行。有很多方式,比如进程,用脚本检测等等
    script "/opt/chk_mysql.sh"          #这里通过脚本监测
    interval 2                          #脚本执行间隔,每2s检测一次
    weight -5                           #脚本结果导致的优先级变更,检测失败(脚本返回非0)则优先级 -5
    fall 2                              #检测连续2次失败才算确定是真失败。会用weight减少优先级(1-255之间)
    rise 1                              #检测1次成功就算成功。但不修改优先级
}
 
vrrp_instance VI_1 {
    state MASTER                        #master1 设置为MASTER
    interface ens33                     #指定虚拟ip的网卡接口
    mcast_src_ip 192.168.31.130         #绑定的地址
    virtual_router_id 51                #路由器标识,MASTER和BACKUP必须是一致的
    priority 101                        #定义优先级,数字越大,优先级越高,在同一个vrrp_instance下,MASTER的优先级必须大于BACKUP的优先级。这样MASTER故障恢复后,就可以将VIP资源再次抢回来 
    advert_int 1         
    authentication {                    #认证类型PASS|AH(IPSEC)
        auth_type PASS 
        auth_pass 1111     
    }
    virtual_ipaddress {                 #虚拟IP的设置即vip
        192.168.31.220
    }
 
    track_script {                      #监控脚本
        chk_mysql_port             
    }
}

监控脚本 cd /opt/
touch chk_mysql.sh 主要监控3306端口是否被监听,若不被监听关闭keepalived服务

#!/bin/bash
counter=$(netstat -na|grep "LISTEN"|grep "3306"|wc -l)
if [ "${counter}" -eq 0 ]; then
    service keepalived stop
fi

设置keepalived为服务并加入开机自动动

vi /lib/systemd/system/keepalived.service

[Unit]
Description=Keepalived
After=network-online.target syslog.target remote-fs.target nss-lookup.target
#Wants=network-online.target

[Service]
Type=forking
PIDFile=/run/keepalived.pid
KillMode=process
EnvironmentFile=-/usr/local/keepalived/etc/sysconfig/keepalived
ExecStart=/usr/local/keepalived/sbin/keepalived $KEEPALIVED_OPTIONS
ExecReload=/bin/kill -HUP $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target

启动keepalived

systemctl start keepalived
ps aux | grep keepalived

centos7安装Keepalived2.0.8+MySQL5.7高可用 双主热备_第10张图片
2.修改mseter2[192.168.31.131]的配置文件

vi /etc/keepalived/keepalived.conf
! Configuration File for keepalived 
global_defs {
    notification_email {                #关于邮件的设置
          [email protected]             #email send to
    }
 
    notification_email_from [email protected]
        smtp_server 127.0.0.1 
        smtp_connect_timeout 30
        router_id MASTER-HA
}
 
vrrp_script chk_mysql_port {            #检测mysql服务是否在运行。有很多方式,比如进程,用脚本检测等等
    script "/opt/chk_mysql.sh"          #这里通过脚本监测
    interval 2                          #脚本执行间隔,每2s检测一次
    weight -5                           #脚本结果导致的优先级变更,检测失败(脚本返回非0)则优先级 -5
    fall 2                              #检测连续2次失败才算确定是真失败。会用weight减少优先级(1-255之间)
    rise 1                              #检测1次成功就算成功。但不修改优先级
}
 
vrrp_instance VI_1 {
    state BACKUP                        #master2 设置为BACKUP 
    interface ens33                     #指定虚拟ip的网卡接口
    mcast_src_ip 192.168.31.131         #绑定的地址
    virtual_router_id 51                #路由器标识,MASTER和BACKUP必须是一致的
    priority 90                         #定义优先级,数字越大,优先级越高,在同一个vrrp_instance下,MASTER的优先级必须大于BACKUP的优先级。这样MASTER故障恢复后,就可以将VIP资源再次抢回来 
    advert_int 1         
    authentication {                    #认证类型PASS|AH(IPSEC)
        auth_type PASS 
        auth_pass 1111     
    }
    virtual_ipaddress {                 #虚拟IP的设置即vip
        192.168.31.220
    }
 
    track_script {                      #监控脚本
        chk_mysql_port             
    }
}

centos7安装Keepalived2.0.8+MySQL5.7高可用 双主热备_第11张图片
systemctl restart keepalived

5.开机启动mysqld和keepalived服务脚本[两台机器都执行]

1.取消开机自启动服务mysqld 和keepalived,原因是系统开机自启动mysqld和keepalived的先后顺序不能确定,所以使用rc.local中的sh脚本启动服务。

1).取消开启自启服务:

systemctl disable mysqld.service    
systemctl disable keepalived.service

2).创建sh脚本加入如下内容,vi /opt/start_services.sh

#!/bin/bash
service mysqld start 
while true
do
    counter=$(netstat -na|grep "LISTEN"|grep "3306"|wc -l)
    if [ "${counter}" -ne 0 ]; then
        service keepalived start
        exit 0
    fi
 
done

3)/etc/rc.d/rc.local 文件末尾追加sh /opt/start_services.sh,并修改 /opt/start_services.sh和/etc/rc.d/rc.local的执行权限

chmod +x /opt/start_services.sh
chmod +x /etc/rc.d/rc.local

6.测试keepalived+双主mysql的可用性

1.用过虚拟IP连接数据库(实际是连接优先级高master1),创建数据库、创建表和添加数据,在master上查看数据是否同步成功。
2.关闭master1 keepalived或者mysqld服务,通过虚拟IP是否仍然可以访问数据库。
3.添加一条数据,自增id是不是按偶数方式增长(是说明一切换到master2上面)
4.恢复master1的keepalived服务,添加一条数据自增ID是不是奇数方式增长(是说明已经切换为master1)

验证截图如下:
关闭master1服务器:
centos7安装Keepalived2.0.8+MySQL5.7高可用 双主热备_第12张图片
发现虚拟vip漂移到master2:
centos7安装Keepalived2.0.8+MySQL5.7高可用 双主热备_第13张图片
通过客户联,在虚拟ip上插入数据:
centos7安装Keepalived2.0.8+MySQL5.7高可用 双主热备_第14张图片
可以看到在master2上出现了:
centos7安装Keepalived2.0.8+MySQL5.7高可用 双主热备_第15张图片
当master1恢复后,虚拟ip又漂移到master1:
centos7安装Keepalived2.0.8+MySQL5.7高可用 双主热备_第16张图片

你可能感兴趣的:(高可用(集群))