1、下载镜像文件
docker pull mysql:5.7
2、创建主服务器实例并启动
docker run -p 3307:3306 --name mysql-master -v /mydata/mysql/master/log:/var/log/mysql -v /mydata/mysql/master/data:/var/lib/mysql -v /mydata/mysql/master/conf:/etc/mysql -e MYSQL_ROOT_PASSWORD=root -d mysql:5.7
参数说明
l -p 3307:3306:将容器的3306端口映射到主机的3307端口
l -v /mydata/mysql/master/conf:/etc/mysql:将配置文件夹挂在到主机
l -v /mydata/mysql/master/log:/var/log/mysql:将日志文件夹挂载到主机
l -v /mydata/mysql/master/data:/var/lib/mysql/:将配置文件夹挂载到主机
l -e MYSQL_ROOT_PASSWORD=root:初始化root用户的密码
MySQL配置
vim /mydata/mysql/conf/my.cnf [client] default-character-set=utf8 [mysql] default-character-set=utf8 [mysqld] init_connect=‘SET collation_connection = utf8_unicode_ci‘ init_connect=‘SET NAMES utf8‘ character-set-server=utf8 collation-server=utf8_unicode_ci skip-character-set-client-handshake skip-name-resolve
server_id=1 #mysql服务id log-bin=mysql-bin read-only=0 #0代表可读可写 binlog-do-db=XXX #需要同步的XXX表 #忽略同步得表 replicate-ignore-db=mysql replicate-ignore-db=sys replicate-ignore-db=information_schema replicate-ignore-db=performance_schema
3、创建从服务器实例并启动
docker run -p 3316:3306 --name mysql-slaver-01 -v /mydata/mysql/slaver/log:/var/log/mysql -v /mydata/mysql/slaver/data:/var/lib/mysql -v /mydata/mysql/slaver/conf:/etc/mysql -e MYSQL_ROOT_PASSWORD=root -d mysql:5.7
MySQL配置
vim /mydata/mysql/slaver/conf/my.cnf [client] default-character-set=utf8 [mysql] default-character-set=utf8 [mysqld] init_connect=‘SET collation_connection = utf8_unicode_ci‘ init_connect=‘SET NAMES utf8‘ character-set-server=utf8 collation-server=utf8_unicode_ci skip-character-set-client-handshake skip-name-resolve
server_id=2 #mysql服务id log-bin=mysql-bin read-only=1 #1代表只读不写 binlog-do-db=XXX #需要同步的XXX表 # 忽略同步的表 replicate-ignore-db=mysql replicate-ignore-db=sys replicate-ignore-db=information_schema replicate-ignore-db=performance_schema
重启
docker restart "服务名称 or 服务id前3位"
4、进入主mysql容器中 操作mysql
docker exec -it mysql-master /bin/bash
1)、授权root可以远程访问
grant all privileges on *.* to ‘root‘@‘%‘ identified by ‘root‘ with grant option; flush privileges;
2)、添加用来同步的用户
GRANT REPLICATION SLAVE ON *.* to ‘backup‘@‘%‘ identified by ‘123456‘;
3)、查看master状态
show master status\G;
5、进入从mysql容器中 操作mysql
docker exec -it mysql-slaver-01 /bin/bash
1)、授权root可以远程访问
grant all privileges on *.* to ‘root‘@‘%‘ identified by ‘root‘ with grant option; flush privileges;
2)、设置主库连接
change master to master_host=‘192.168.31.128‘,master_user=‘backup‘,master_password=‘123456‘,master_log_file=‘mysql-bin.000001‘,master_log_pos=0,master_port=3307;
3)、启动从库同步
start slave;
4)、查看从库状态
至此主从配置完成;
总结:
1)、主从数据库在自己配置文件中声明需要同步哪个数据库,忽略哪个数据库等信息。并且server-id不能一样
2)、主库授权某个账号密码来同步自己的数据
3)、从库使用这个账号密码连接主库来同步数据