1.创建Master中Mysql的数据目录并赋权
mkdir -p /data/mysql-master/data
chmod -R 777 /data
2.创建Master配置文件
vi /data/mysql-master/my-master.cnf
复制以下内容至配置文件
[mysqld]
user = mysql
port = 3306
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
lc-messages-dir = /usr/share/mysql
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
server-id = 1
log-bin = mysql-bin
default-storage-engine = INNODB
character-set-server = utf8
collation-server = utf8_general_ci
#bind-address = 127.0.0.1
#log-error = /var/log/mysql/error.log
lower_case_table_names = 1
explicit_defaults_for_timestamp = true
symbolic-links = 0
sql_mode = STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
skip-name-resolve
max_connections=500
character-set-server=utf8mb4
default-storage-engine=InnoDB
[client]
port = 3306
socket = /var/run/mysqld/mysqld.sock
default-character-set=utf8
[mysqld_safe]
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
nice = 0
3.创建Master的启动脚本
vi /data/mysql-master/run.sh
复制以下内容至启动脚本
docker run -d \
--name mysql-master \
-e MYSQL_ROOT_PASSWORD=ddl2022. \
-v /data/mysql-master/data:/var/lib/mysql \
-v /data/mysql-master/my-master.cnf:/etc/mysql/my.cnf \
-v /etc/localtime:/etc/localtime \
-p 3306:3306 \
mysql:5.7.39
4.启动Master容器
sh /data/mysql-master/run.sh
5.创建Slave中Mysql的数据目录
mkdir -p /data/mysql-slave/data
6.创建Slave配置文件
复制Master配置文件 修改”server-id = 1”为”server-id = 2”
7.创建Slave的启动脚本
vi /data/mysql-slave/run.sh
复制以下文件至配置文件
docker run -d \
--name mysql-slave\
-e MYSQL_ROOT_PASSWORD=ddl2022. \
-v /data/mysql-slave/data:/var/lib/mysql \
-v /data/mysql-slave/my-slave.cnf:/etc/mysql/my.cnf \
-v /etc/localtime:/etc/localtime \
-p 3306:3306 \
mysql:5.7.39
注:如部署在同一服务器则将3306端口改为3307
8.启动Slave容器
sh /data/mysql-slave/run.sh
9.查看Master和Slave中的Mysql容器是否正常运行
如部署在同一台服务器中执行以下命令查看master和slave容器的IP地址
docker inspect mysql-master |grep 'IPAddress'
docker inspect mysql-slave |grep 'IPAddress'
如不在一台服务器则执行ifconfig查看服务器ip地址
12.在Master中执行
docker exec -it mysql-master bash
进入容器后执行
mysql -uroot -pddl2022.
进入mysql后执行
grant replication slave on *.* to 'slave'@'%' identified by 'slave';
flush privileges;
show master status;
执行结果
记录File Position值
13.在Slave中执行
Docker exec -it mysql-slave bash
进入容器后执行
mysql -uroot -pddl2022.
进入mysql后执行
change master to master_host='172.17.0.2', master_user='slave', master_password='slave', master_log_file='mysql-bin.000003', master_log_pos=582, master_port=3306;
start slave;
show slave status \G;
将host改为Master容器IP或Master服务器IP,将master_log_fie和master_log_pos对应改为Master的File和File和Position
执行结果
从执行结果中看到Slave_IO_Running :Yes和Slave_SQL_Running :Yes则表示主从配置成功
14.测试
使用Navicat工具链接主库和从库 在主库添加数据查看从库是否同步