mysql主从同步
1.实验环境:
2台centos7.2系统,ip分别为192.168.2.40 192.168.2.41
防火墙和selinux均关闭 同步时间
2.实验步骤:
192.168.2.40上操作:
[root@mysql-master ~]# yum -y install mariadb mariadb-server
[root@mysql-master ~]# vi /etc/my.cnf 添加下面内容:
[mysqld]
log-bin=mysql-bin
server-id=1
启动服务:
[root@mysql-master ~]# systemctl start mariadb
更改数据库密码:
[root@mysql-master ~]# mysql_secure_installation
进入数据库:
[root@mysql-master ~]# mysql -uroot -p
增加一个账号专门用于同步:
MariaDB [(none)]> grant replication slave on *.* to 'backup'@'192.168.2.41' identified by 'backup'; flush privileges;
显示master状态:
MariaDB [(none)]> show master status;
+------------------+----------+--------------+------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000003 | 1703 | | |
+------------------+----------+--------------+------------------+
记录下File和Position然后在41上面设置从40同步
192.168.2.41上操作:
[root@mysql-agent ~]# yum -y install mariadb mariadb-server
[root@mysql-agent ~]# vi /etc/my.cnf 添加下面内容:
[mysqld]
log-bin=mysql-bin
server-id=10 (此处要设置的跟40不同)
启动服务:
[root@mysql-master ~]# systemctl start mariadb
更改数据库密码:
[root@mysql-master ~]# mysql_secure_installation
进入数据库:
[root@mysql-master ~]# mysql -uroot -p
执行:
MariaDB [(none)]> change master to master_host='192.168.2.41',master_user='backup',master_password='backup',master_log_file='mysqlbin.000003',master_log_pos=1703;
注意:1703对应上面在40上面记下的Position,mysql-bin.000003对应40上面记录的File
启动复制线程:
MariaDB [(none)]> START SLAVE;
执行成功后,输入命令显示从库状态:
MariaDB [(none)]> show slave status \G;
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
上面的两行均为yes表示已同步
增加一个账号专门用于同步:
MariaDB [(none)]> grant replication slave on *.* to 'backup'@'192.168.2.40' identified by 'backup'; flush privileges;
显示41做为主库时的状态:
MariaDB [(none)]> show master status;
+------------------+----------+--------------+------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000003 | 1703 | | |
+------------------+----------+--------------+------------------+
192.168.2.40数据库上操作:
MariaDB [(none)]> change master to master_host='192.168.2.41',master_user='backup',master_password='backup',master_log_file='mysql-bin.000003',master_log_pos=1703;
MariaDB [(none)]> START SLAVE;
MariaDB [(none)]> show slave status \G;
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
上面的两行均为yes表示已同步
验证:分别在两台数据库里建库、建表,看看另一台是否会自动生成。