mysql主从复制
- 1、修改主服务器master:
- #vi /etc/my.cnf
- [mysqld]
- log-bin=mysql-bin //[必须]启用二进制日志
- server-id=1 //[必须]服务器唯一ID,默认是1,一般取IP最后一段
- 2、修改从服务器slave:
- #vi /etc/my.cnf
- [mysqld]
- log-bin=mysql-bin //[必须]启用二进制日志
- server-id=2 //[必须]服务器唯一ID,默认是1,一般取IP最后一段
- 3、重启两台服务器的mysql
- /etc/init.d/mysql restart
- 4、在主服务器上建立帐户并授权slave:
- #/usr/local/mysql/bin/mysql -uroot -p
- mysql>GRANT REPLICATION SLAVE ON *.* to 'mysql'@'%' identified by '123456'; //一般不用root帐号,“%”表示所有客户端都可能连,只要帐号,密码正确,此处可用具体客户端IP代替,如8.8.8.8,加强安全。
- 5、登录主服务器的mysql,查询master的状态
- show master status;
- +------------------+----------+--------------+------------------+
- | File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
- +------------------+----------+--------------+------------------+
- | mysql-bin.000004 | 106 | | |
- +------------------+----------+--------------+------------------+
- 注:执行完此步骤后不要再操作主服务器MYSQL,防止主服务器状态值变化
- 6、配置从服务器Slave:
- mysql>change master to master_host='8.8.8.8',master_user='mysql',master_password='123456',
- master_log_file='mysql-bin.,000004',master_log_pos=106; //注意不要断开,“308”无单引号。
- Mysql>start slave; //启动从服务器复制功能
- 7.增加一个检测mysql主从的脚本。
- #!/bin/bash
mysql_status=`netstat -nl | awk 'NR>2{if ($4 ~ /.*:3306/) {print "Yes";exit 0}}'`
if [ "$mysql_status" == "Yes" ];then
slave_status=`mysql -uroot -p'' -e"show slave status\G" | grep "Running" | awk '{if ($2 != "Yes") {print "No";exit 1}}'`
if [ "$slave_status" == "No" ];then
echo "slave is not working!"
[ ! -f "/tmp/slave" ] && echo "Slave is not working!" | mail -s "Warn!MySQL Slave is not working" slave@centos.com
touch /tmp/slave
else
echo "slave is working."
[ -f "/tmp/slave" ] && rm -f /tmp/slave
fi
[ -f "/tmp/mysql_down" ] && rm -f /tmp/mysql_down
else
[ ! -f "/tmp/mysql_down" ] && echo "Mysql Server is down!" | mail -s "Warn!MySQL server is down!" slave@centos.com
touch /tmp/mysql_down
fi
~