系统 | CentOS Linux release 7.6.1810 (Core) |
---|---|
ip | 192.168.199.120 |
mysql | 5.7 |
docker | Docker version 1.13.1 |
#0.初始化网络
docker swarm init
#1.创建 overlay 网络
docker network create --driver overlay common-network --attachable
#2.编辑两个配置文件 master.cnf 与 slave.cnf
#master.cnf 内容如下:
!includedir /etc/mysql/conf.d/
!includedir /etc/mysql/mysql.conf.d/
[mysqld]
log-bin=mysql-bin
server-id=1
gtid-mode=ON
enforce-gtid-consistency=ON
#slave.cnf内容如下:
!includedir /etc/mysql/conf.d/
!includedir /etc/mysql/mysql.conf.d/
[mysqld]
server-id=2
gtid-mode=ON
enforce-gtid-consistency=ON
#3.启动 :mysql-master 、mysql-slave
#下载镜像:
docker pull hub.c.163.com/library/mysql:5.7
docker tag hub.c.163.com/library/mysql:5.7 mysql:5.7
#启动mysql-master:
docker run -d --name mysql-master --network common-network -e MYSQL_ROOT_PASSWORD=Passw0rd -v `pwd`/master.cnf:/etc/mysql/my.cnf -p 3306:3306 -d mysql:5.7
#启动mysql-slave:
docker run -d --name mysql-slave --network common-network -e MYSQL_ROOT_PASSWORD=Passw0rd -v `pwd`/slave.cnf:/etc/mysql/my.cnf -p 3307:3306 -d mysql:5.7
#4.添加从库repl用于复制的用户
docker run -it --rm --network common-network mysql mysql -hmysql-master -uroot -pPassw0rd -e "CREATE USER 'repl'@'%' IDENTIFIED BY 'password' REQUIRE SSL; " -e "GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%';"
#5.连接 master & slave
docker run -it --rm --network common-network mysql mysql -hmysql-slave -uroot -pPassw0rd -e "CHANGE MASTER TO MASTER_HOST='mysql-master', MASTER_PORT=3306, MASTER_USER='repl', MASTER_PASSWORD='password', MASTER_AUTO_POSITION=1, MASTER_SSL=1;" -e "START SLAVE;"
#6.验证 slave 状态,如下状态为正常:Slave_IO_Running: Yes Slave_SQL_Running: Yes
docker run -it --rm --network common-network mysql mysql -hmysql-slave -uroot -pPassw0rd -e "show slave status\G"
#7.验证数据同步
#在 master 创建数据库 tzzxz
docker run -it --rm --network common-network mysql mysql -hmysql-master -uroot -pPassw0rd -e "create database tzzxz default character set utf8mb4 collate utf8mb4_general_ci;"
#在 slave 查看数据库列表
docker run -it --rm --network common-network mysql mysql -hmysql-slave -uroot -pPassw0rd -e "show databases;"
slave信息如下,同步成功
mysql: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
| Database |
+--------------------+
| tzzxz |
| information_schema |
| mysql |
| performance_schema |
| sys |
+--------------------+
相关资料:https://dev.mysql.com/doc/refman/5.7/en/replication.html