Mysql之双向主从加keepalived高可用
最近在做MySQL数据库的双向主从,了解到keepalived能够自动判断并切换到可用数据库,自己试了一下,整理出文档来。..
最近在做MySQL数据库的双向主从,了解到keepalived能够自动判断并切换到可用数据库,自己试了一下,整理出文档来。
先声明一下环境
iptables开启3306端口或者关掉,关闭selinux
MySQL-01:192.168.204.138
MySQL-02:192.168.204.139
VIP:192.168.204.200 #web服务器连接的ip,自己可以使用工具连接试一下。
MySQL的安装过程就略过了,根据个人情况自己安装即可。
1.修改数据库的配置文件/etc/my.cnf:
1.1修改MySQL-01的数据库文件,在[mysql]下添加如下内容
server_id = 1 log_bin = mysql-bin1.2修改MySQL-02的数据库文件,在[mysql]下添加如下内容
server_id = 2 log_bin = mysql-bin2.搭建单向主从
2.1在MySQL-01上
2.1.1操作授权
mysql -u root -p #输入密码 mysql> grant replication slave on *.* to 'slave'@'192.168.204.139' identified by '123456'; mysql> flush privileges;2.1.2数据传递给MySQL-02
mysql -u root -p #输入密码 flush tables with read lock; #锁表操作 mysql> show master status; +------------------+----------+--------------+------------------+-------------------+ | File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set | +------------------+----------+--------------+------------------+-------------------+ | mysql-bin.000012 | 120 | | | | +------------------+----------+--------------+------------------+-------------------+ 1 row in set (0.00 sec) mysqldump -u root -p --all-databases > mysqldump.sql mysql -u root -p mysql> unlock tables; mysql> quit scp myqsldump.sql 192.168.204.139:/root/ 2.2在MySQL-02上操作
2.2.1恢复数据库数据
mysql -u root -p 2.2.2建立主从同步 mysql -u root -p mysql> change master to master_host='192.168.204.138',master_user='slave',master_password='123456',master_log_file='mysql-bin.000012',master_log_pos=120,master_port=3306; start slave;检查是否成功
show slave status\G;Slave_IO_Running: Yes Slave_SQL_Running: Yes 都为Yes表示同步成功。
注:master_port=3306,默认时不需要加,但是修改过端口的则需要该选项
3.搭建互为主从
3.1在MySQl-01上操作
3.1.1用户授权
mysql -u root -p123456 mysql> grant replication slave on *.* to 'slave'@'192.168.204.138' identified by '123456'; //建立权限 mysql> flush privileges; 注:因为做的是所有库的主从,,所以在MySQL-01上的操作会同步到MySQL-02上
3.2在MySQL-02上的操作
mysql -u root -p mysql> show master status\G; +------------------+----------+--------------+------------------+-------------------+ | File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set | +------------------+----------+--------------+------------------+-------------------+ | mysql-bin.000009 | 120 | | | | +------------------+----------+--------------+------------------+-------------------+ 1 row in set (0.00 sec)