keepalived+mysql實現雙主高可用


 

環境:

DB1:centos6.8、mysql5.5、192.168.2.204  hostname:bogon

DB2:centos6.8、mysql5.5、192.168.2.205  hostname:localhost.localdomain

vip:192.168.2.33

 

一、先配置DB1和DB2的雙主熱備

 

1、分別在DB1和DB2上安裝mysql,我這里是用的ansible自動部署

[root@www ansible]# ansible-playbook lnmp.yml 

PLAY [new] *********************************************************************

TASK [setup] *******************************************************************
ok: [192.168.2.205]
ok: [192.168.2.204]

TASK [mysql : Create backup folder] ********************************************
ok: [192.168.2.204]
ok: [192.168.2.205]

TASK [mysql : create log folder] ***********************************************
changed: [192.168.2.204]
changed: [192.168.2.205]

TASK [mysql : copy mysql_tar_gz to client] *************************************
changed: [192.168.2.204]
changed: [192.168.2.205]

TASK [mysql : copy install_script to client] ***********************************
changed: [192.168.2.204]
changed: [192.168.2.205]

TASK [mysql : copy my.cnf to /data/backup] *************************************
changed: [192.168.2.204]
changed: [192.168.2.205]

TASK [mysql : install mysql] ***************************************************
changed: [192.168.2.204]
changed: [192.168.2.205]

PLAY RECAP *********************************************************************
192.168.2.204              : ok=7    changed=5    unreachable=0    failed=0   
192.168.2.205              : ok=7    changed=5    unreachable=0    failed=0   

2、修改mysql的配置文件

首先修改DB1主機的配置文件,在/etc/my.cnf文件中的[mysqld]段添加以下內容

[root@bogon ~]# vim /etc/my.cnf
server-id = 1    #節點標示,主從節點不能相同,必須全局唯一
log-bin=mysql-bin  #開啟mysql的binlog日志功能
relay-log = mysql-relay-bin   #開啟relay-log日志,relay-log日志記錄的是從服務器I/O線程將主服務器的二進制日志讀取過來記錄到從服務器本地文件,然后SQL線程會讀取relay-log日志的內容並應用到從服務器
replicate-wild-ignore-table=mysql.%  #復制過濾選項
replicate-wild-ignore-table=test.%
replicate-wild-ignore-table=information_schema.%

 

然后修改DB2主機的配置文件,

[root@localhost ~]# vim /etc/my.cnf
server-id = 2
log-bin=mysql-bin
relay-log = mysql-relay-bin
replicate-wild-ignore-table=mysql.%
replicate-wild-ignore-table=test.%
replicate-wild-ignore-table=information_schema.%

最后分別重啟DB1和DB2使配置生效

 

3、創建復制用戶並授權

注:在執行主主互備之前要保證兩台server上數據一致

 

首先在DB1的mysql庫中創建復制用戶

mysql> grant replication slave on *.* to 'repl_user'@'192.168.2.205' identified by 'repl_passwd';
Query OK, 0 rows affected (0.04 sec)

mysql> show master status;
+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000004 |      271 |              |                  |
+------------------+----------+--------------+------------------+
1 row in set (0.00 sec)

然后在DB2的mysql庫中將DB1設為自己的主服務器

mysql> change master to \
    -> master_host='192.168.2.204',  
    -> master_user='repl_user',
    -> master_password='repl_passwd',
    -> master_log_file='mysql-bin.000004',  
    -> master_log_pos=271;
Query OK, 0 rows affected (0.07 sec)

這里需要注意master_log_file和master_log_pos兩個選項,這兩個選項的值是在DB1上通過“show master status” 查詢到的結果

 

接着在DB2上啟動slave服務

mysql> start slave;
Query OK, 0 rows affected (0.01 sec)

下面查看DB2上slave的運行狀態,

mysql> show slave status\G
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.2.204
                  Master_User: repl_user
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000005
          Read_Master_Log_Pos: 271
               Relay_Log_File: mysql-relay-bin.000002
                Relay_Log_Pos: 253
        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: mysql.%,test.%,information_schema.%  #跳過的表
                   Last_Errno: 0
                   Last_Error: 
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 271
              Relay_Log_Space: 409
              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
1 row in set (0.00 sec)

到這里,從DB1到DB2的mysql主從復制已經完成。接下來開始配置從DB2到DB1的mysql主從復制

在DB2的mysql庫中創建復制用戶

mysql> grant replication slave on *.* to 'repl_user'@'192.168.2.204' identified by 'repl_passwd';
Query OK, 0 rows affected (0.00 sec)

mysql> show master status;
+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000005 |      271 |              |                  |
+------------------+----------+--------------+------------------+
1 row in set (0.00 sec)

然后在DB1的mysql庫中將DB2設為自己的主服務器

mysql> change master to \
    -> master_host='192.168.2.205',
    -> master_user='repl_user',
    -> master_password='repl_passwd',
    -> master_log_file='mysql-bin.000005',
    -> master_log_pos=271;
Query OK, 0 rows affected (0.07 sec)

最后,在DB1上啟動slave服務

mysql> start slave;
Query OK, 0 rows affected (0.01 sec)

查看DB1上slave的運行狀態

mysql> show slave status\G
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.2.205
                  Master_User: repl_user
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000005
          Read_Master_Log_Pos: 271
               Relay_Log_File: mysql-relay-bin.000002
                Relay_Log_Pos: 253
        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: mysql.%,test.%,information_schema.%
                   Last_Errno: 0
                   Last_Error: 
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 271
              Relay_Log_Space: 409
              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
1 row in set (0.00 sec)

 

二、配置keepalived實現mysql雙主高可用

1、安裝keepalived

[root@bogon src]# tar zxf keepalived-1.2.24.tar.gz 
[root@bogon src]# cd keepalived-1.2.24
[root@bogon keepalived-1.2.24]# ./configure --sysconf=/etc --with-kernel-dir=/lib/modules/2.6.32-642.3.1.el6.x86_64/
[root@bogon keepalived-1.2.24]# make && make install
[root@bogon keepalived-1.2.24]# ln -s /usr/local/sbin/keepalived /sbin/
[root@bogon keepalived-1.2.24]# chkconfig --add keepalived
[root@bogon keepalived-1.2.24]# chkconfig --level 35 keepalived on
[root@bogon keepalived-1.2.24]# yum  -y install ipvsadm ####之前沒安裝ipvsadm,導致 keepalived配置中lvs配置部分不生效,其中定義的notify_down 字段死活不生效,查了好久在發現是沒安裝ipvsadm導致的,淚奔!!!
[root@bogon keepalived-1.2.24]# ipvsadm

2、配置keepalived

DB1上keepalived.conf配置為

[root@bogon keepalived-1.2.24]# cat /etc/keepalived/keepalived.conf 
! Configuration File for keepalived

global_defs {
   notification_email {
     acassen@firewall.loc
     failover@firewall.loc
     sysadmin@firewall.loc
   }
   notification_email_from Alexandre.Cassen@firewall.loc
   smtp_server 192.168.200.1
   smtp_connect_timeout 30
   router_id LVS_DEVEL
   vrrp_skip_check_adv_addr
   vrrp_strict
   vrrp_garp_interval 0
   vrrp_gna_interval 0
}




vrrp_instance HA_1 {
    state BACKUP    #在DB1和DB2上均配置為BACKUP
    interface eth1
    virtual_router_id 90 
    priority 100
    advert_int 1
    nopreempt    #不搶占模式,只有優先級高的機器上設置即可,優先級低的機器可不設置
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
    192.168.2.33
    }
}

virtual_server 192.168.2.33 3306 {
     delay_loop 2
     lb_algo wrr
     lb_kind DR
     persistence_timeout 60  #會話保持時間 
     protocol TCP
     real_server 192.168.2.204 3306 {
         weight 3
         notify_down /root/shutdown.sh  #檢測到服務down后執行的腳本 
         TCP_CHECK {
             connect_timeout 10  #連接超時時間
             nb_get_retry 3    #重連次數
             delay_before_retry 3   #重連間隔時間  
             connect_port 3306     #健康檢查端口
         } 
     }
}

 

 

DB2上keepalived.conf配置為

[root@localhost keepalived-1.2.24]# cat /etc/keepalived/keepalived.conf 
! Configuration File for keepalived

global_defs {
   notification_email {
     acassen@firewall.loc
     failover@firewall.loc
     sysadmin@firewall.loc
   }
   notification_email_from Alexandre.Cassen@firewall.loc
   smtp_server 192.168.200.1
   smtp_connect_timeout 30
   router_id LVS_DEVEL
   vrrp_skip_check_adv_addr
   vrrp_strict
   vrrp_garp_interval 0
   vrrp_gna_interval 0
}




vrrp_instance HA_1 {
    state BACKUP
    interface eth1
    virtual_router_id 90 
    priority 90
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
    192.168.2.33
    }
}

virtual_server 192.168.2.33 3306 {
     delay_loop 2
     lb_algo wrr
     lb_kind DR
     persistence_timeout 60
     protocol TCP
     real_server 192.168.2.205 3306 {
         weight 3
         notify_down /root/shutdown.sh
         TCP_CHECK {
             connect_timeout 10
             nb_get_retry 3
             delay_before_retry 3
             connect_port 3306
         } 
     }
}

 

編寫檢測服務down后所要執行的腳本shutdown.sh

[root@bogon ~]# cat /root/shtdown.sh 
#!/bin/bash
killall keepalived

注:此腳本是上面配置文件notify_down選項所用到的,keepalived使用notify_down選項來檢查real_server的服務狀態,當發現real_server服務故障時,便觸發此腳本;我們可以看到,腳本就一個命令,通過killall keepalived強制殺死keepalived進程,從而實現了MySQL故障自動轉移。另外,我們不用擔心兩個MySQL會同時提供數據更新操作,因為每台MySQL上的keepalived的配置里面只有本機MySQL的IP+VIP,而不是兩台MySQL的IP+VIP

 

啟動keepalived並查看日志

[root@bogon keepalived-1.2.24]# chmod 755 /etc/init.d/keepalived 
[root@bogon keepalived-1.2.24]# service keepalived start
正在啟動 keepalived:                                      [確定]
[root@bogon keepalived-1.2.24]# tail -f /var/log/messages
Oct 24 22:37:35 bogon Keepalived_vrrp[20835]: Sending gratuitous ARP on eth1 for 192.168.2.33
Oct 24 22:37:35 bogon Keepalived_vrrp[20835]: Sending gratuitous ARP on eth1 for 192.168.2.33
Oct 24 22:37:35 bogon Keepalived_vrrp[20835]: Sending gratuitous ARP on eth1 for 192.168.2.33
Oct 24 22:37:35 bogon Keepalived_vrrp[20835]: Sending gratuitous ARP on eth1 for 192.168.2.33
Oct 24 22:37:40 bogon Keepalived_vrrp[20835]: Sending gratuitous ARP on eth1 for 192.168.2.33
Oct 24 22:37:40 bogon Keepalived_vrrp[20835]: VRRP_Instance(HA_1) Sending/queueing gratuitous ARPs on eth1 for 192.168.2.33
Oct 24 22:37:40 bogon Keepalived_vrrp[20835]: Sending gratuitous ARP on eth1 for 192.168.2.33
Oct 24 22:37:40 bogon Keepalived_vrrp[20835]: Sending gratuitous ARP on eth1 for 192.168.2.33
Oct 24 22:37:40 bogon Keepalived_vrrp[20835]: Sending gratuitous ARP on eth1 for 192.168.2.33
Oct 24 22:37:40 bogon Keepalived_vrrp[20835]: Sending gratuitous ARP on eth1 for 192.168.2.33

 

三、測試功能

1、在遠程客戶端通過vip登陸測試

[root@www ansible]# mysql -h 192.168.2.33 -uroot -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2372
Server version: 5.5.37-log Source distribution

Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

  mysql> show variables like "%hostname%"
  -> ;
  +---------------+-------+
  | Variable_name | Value |
  +---------------+-------+
  | hostname | bogon |
  +---------------+-------+
  1 row in set (0.00 sec)

 

從sql輸出結果看,可以通過vip登陸,並且登陸了DB1服務器

 

2、創建一個數據庫,然后在這個庫重創建一個表,並插入數據

mysql> create database repldb;
Query OK, 1 row affected (0.02 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| repldb             |
| test               |
+--------------------+
5 rows in set (0.06 sec)

mysql> use repldb;
Database changed
mysql> create table repl_table(id int,email varchar(80),password varchar(40) not null);
Query OK, 0 rows affected (0.03 sec)

mysql> show tables;
+------------------+
| Tables_in_repldb |
+------------------+
| repl_table       |
+------------------+
1 row in set (0.01 sec)

mysql> insert into repl_table(id,email,password) values(1,"master@163.com","qweasd");
Query OK, 1 row affected (0.00 sec)

 

登陸DB2主機的mysql,可數據是否復制成功

mysql> show variables like "%hostname%";
+---------------+-----------------------+
| Variable_name | Value                 |
+---------------+-----------------------+
| hostname      | localhost.localdomain |
+---------------+-----------------------+
1 row in set (0.01 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| repldb             |
| test               |
+--------------------+
5 rows in set (0.05 sec)

mysql> use repldb;
Database changed
mysql> show tables;
+------------------+
| Tables_in_repldb |
+------------------+
| repl_table       |
+------------------+
1 row in set (0.00 sec)


mysql> select * from repl_table;
+------+----------------+----------+
| id   | email          | password |
+------+----------------+----------+
|    1 | master@163.com | qweasd   |
+------+----------------+----------+
1 row in set (0.08 sec)

3、停止DB1主機上的mysql,查看故障是否自動轉移

[root@bogon ~]# service mysqld stop
Shutting down MySQL.. SUCCESS! 

 登陸192.168.2.33查看:

mysql> show variables like "%hostname%";
ERROR 2006 (HY000): MySQL server has gone away
No connection. Trying to reconnect...
Connection id:    610
Current database: repldb

+---------------+-----------------------+
| Variable_name | Value                 |
+---------------+-----------------------+
| hostname      | localhost.localdomain |
+---------------+-----------------------+
1 row in set (0.01 sec)

可以看到現在登陸的是DB2 故障自動切換成功

接着,插入數據看DB1是否能復制

mysql> insert into repl_table(id,email,password) values(2,"slave@163.com","qweasd");
Query OK, 1 row affected (0.06 sec)

mysql> use repldb;
Database changed
mysql> select * from repl_table;
+------+----------------+----------+
| id   | email          | password |
+------+----------------+----------+
|    1 | master@163.com | qweasd   |
|    2 | slave@163.com  | qweasd   |
+------+----------------+----------+
2 rows in set (0.00 sec)

登陸DB1查看表數據

[root@bogon ~]# service mysqld start
Starting MySQL. SUCCESS! 
[root@bogon ~]# mysql -uroot -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.5.37-log Source distribution

Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> use repldb;
Database changed
mysql> select * from repl_table;
+------+----------------+----------+
| id   | email          | password |
+------+----------------+----------+
|    1 | master@163.com | qweasd   |
|    2 | slave@163.com  | qweasd   |
+------+----------------+----------+
2 rows in set (0.02 sec)

復制成功!

 

到此全部完成!!!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM