启动master
docker run -p 3339:3306 -v /root/mysql/master/:/etc/mysql/ --name mysql-master -e MYSQL_ROOT_PASSWORD=123456 -d mysql:5.7
/root/mysql/master/my.cnf配置内容
#############
[mysqld]
## 同一局域网内注意要唯一
server-id=100
## 开启二进制日志功能,可以随便取(关键)
log-bin=mysql-bin
[mysqldump]
user = root
password = 123456
################
重启mysql
service mysql restart
docker start mysql-master
在主mysql容器中登录mysql,创建备份用户
CREATE USER 'slave'@'%' IDENTIFIED BY '123456';
GRANT REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'slave'@'%';
给主库加锁,防止数据修改
flush tables with read lock;
备份数据库中已有的数据,test为库名
docker exec mysql-master /usr/bin/mysqldump test >backup.sql
查看主binlog
show master status;
+------------------+----------+--------------+------------------+-------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql-bin.000001 | 617 | | | |
+------------------+----------+--------------+------------------+-------------------+
启动slave
docker run -p 3340:3306 -v /root/mysql/slave/:/etc/mysql/ --name mysql-slave -e MYSQL_ROOT_PASSWORD=123456 -d mysql:5.7
/root/mysql/slave/my.cnf配置内容
############
[mysqld]
## 同一局域网内注意要唯一
server-id=101
## 开启二进制日志功能,可以随便取
log-bin=mysql-slave-bin
## relay_log配置中继日志
relay_log=edu-mysql-relay-bin
[mysql]
user = root
password = 123456
################
重启mysql
docker stop mysql-slave
docker start mysql-slave
创建库
CREATE DATABASE test;
执行备份的sql
cat backup.sql | docker exec -i mysql-slave /usr/bin/mysql test
在slave中的mysql执行,绑定主服务器
change master to master_host='192.168.88.154', master_user='slave', master_password='123456', master_port=3339, master_log_file='mysql-bin.000001', master_log_pos= 617, master_connect_retry=30;
开启备份
start slave;
查看状态
show slave status \G;
显示如下正常。
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
在主mysql中解锁主数据库
unlock tables;
可以在主库中新增数据,查看从库是否已经同步