本次安装MySQL 版本如下:
- MySQL5.7.28
1.初始化docker集群管理工具swarm
因为要做数据库主从,因此,需要docker对集群支持
docker swarm init
2.创建 overlay 网络
docker network create --driver overlay common-network --attachable
3.新建文件夹
cd /home
mkdir mysql
cd /home/mysql
4.编辑主从配置文件 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
5.启动 master & slave
启动 master:
docker run -d \
--name mysql-master \
--network common-network \
-e MYSQL_ROOT_PASSWORD=1234=Qwer! \
-v `pwd`/master.cnf:/etc/mysql/my.cnf \
-p 3306:3306 \
-d mysql:5.7.28
启动 slave:
docker run -d \
--name mysql-slave \
--network common-network \
-e MYSQL_ROOT_PASSWORD=1234=Qwer! \
-v `pwd`/slave.cnf:/etc/mysql/my.cnf \
-p 3307:3306 \
-d mysql:5.7.28
5.添加从库用于复制的用户
docker run -it --rm --network common-network mysql:5.7.28 mysql -hmysql-master -uroot -p1234=Qwer! \
-e "CREATE USER 'repl'@'%' IDENTIFIED BY '1234=Qwer\!' REQUIRE SSL;" \
-e "GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%';"
6.连接 master & slave
docker run -it --rm --network common-network mysql:5.7.28 mysql -hmysql-slave -uroot -p1234=Qwer! \
-e "CHANGE MASTER TO MASTER_HOST='mysql-master', MASTER_PORT=3306, MASTER_USER='repl', MASTER_PASSWORD='1234=Qwer\!', MASTER_AUTO_POSITION=1, MASTER_SSL=1;" \
-e "START SLAVE;"
7.验证slave状态
docker run -it --rm --network common-network mysql:5.7.28 mysql -hmysql-slave -uroot -p1234=Qwer! -e "show slave status\G"
如下状态为正常:
Slave_IO_Running: Waiting for master to send event
Slave_SQL_Running: Slave has read all relay log; waiting for more updates