转载请表明出处 https://blog.csdn.net/Amor_Leo/article/details/85177001 谢谢
Docker安装mysql5.7并且配置主从复制
拉取mysql镜像
docker pull mysql:5.7
创建文件docker.cnf
mysql主机(192.168.0.109)
创建文件夹
mkdir /usr/local/mysql
cd mysql/
mkdir conf data
创建docker.cnf
vim /usr/local/mysql/conf/docker.cnf
- 具体添加
[mysqld]
server-id=1
log-bin=master-bin #只是读写,就只要主库配置即可.如果要做主从切换,那么主库和从库都需要开启.
skip-host-cache
skip-name-resolve
collation-server = utf8_unicode_ci
init-connect='SET NAMES utf8'
character-set-server = utf8
[mysql]
default-character-set=utf8
[client]
default-character-set=utf8
mysql从机(192.168.0.110)
创建文件夹
mkdir /usr/local/mysql
cd mysql/
mkdir conf data
创建docker.cnf
vim /usr/local/mysql/conf/docker.cnf
- 具体添加
[mysqld]
server-id=2
log-bin=master-bin
skip-host-cache
skip-name-resolve
collation-server = utf8_unicode_ci
init-connect='SET NAMES utf8'
character-set-server = utf8
[mysql]
default-character-set=utf8
[client]
default-character-set=utf8
创建容器并运行
放行端口号
firewall-cmd --zone=public --add-port=3306/tcp --permanent
firewall-cmd --reload
mysql主机
docker run --name mysqlmaster -p 3306:3306 -v /usr/local/mysql/conf:/etc/mysql/conf.d -v /usr/local/mysql/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=root --privileged=true -d mysql:5.7
mysql从机
docker run --name mysqlslave -p 3306:3306 -v /usr/local/mysql/conf:/etc/mysql/conf.d -v /usr/local/mysql/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=root --privileged=true -d mysql:5.7
开启主从复制
mysql主机
- 进入mysql容器
docker exec -it mysqlmaster /bin/bash
- 启动mysql
mysql -uroot -proot
- 创建用户
create user 'lhl'@'%' identified by 'root';
- 权限
grant replication slave on *.* to 'lhl'@'%';
- 刷新权限
flush privileges;
- 查看状态
show master status;
mysql从机
-
进入mysql容器
docker exec -it mysqlslave /bin/bash
-
启动mysql
mysql -uroot -proot
-
执行主从
change master to master_host='192.168.0.109',master_port=3306,master_user='lhl',master_password='root',master_log_file='master-bin.000003',master_log_pos=745;
- 如果报错,执行下面命令并再次执行上面的命令
stop slave;
-
开启复制
start slave;
-
查看主从是否成功
show slave status \G;
以下两个都为yes就代表成功了
Slave_IO_Running: Yes Slave_SQL_Running: Yes 说明主从成功