要在Docker中搭建MySQL主从复制,可以按照以下步骤操作:
docker network create mysql-replication
docker run -d --name mysql-master --network mysql-replication -e MYSQL_ROOT_PASSWORD=password mysql:latest
docker run -d --name mysql-slave --network mysql-replication -e MYSQL_ROOT_PASSWORD=password mysql:latest
docker exec -it mysql-master bash
mysql -u root -p
CREATE USER 'repl'@'%' IDENTIFIED BY 'password';
GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%';
FLUSH PRIVILEGES;
SET GLOBAL binlog_format = 'ROW';
SET GLOBAL log_slave_updates = 1;
SET GLOBAL gtid_mode = ON;
SET GLOBAL enforce-gtid-consistency = ON;
docker exec -it mysql-slave bash
mysql -u root -p
CHANGE MASTER TO MASTER_HOST='mysql-master', MASTER_USER='repl', MASTER_PASSWORD='password', MASTER_AUTO_POSITION=1;
START SLAVE;
SHOW MASTER STATUS;
在从服务器上执行以下命令检查主从复制状态:
SHOW SLAVE STATUS \G;
如果输出结果中的Slave_IO_Running
和Slave_SQL_Running
均显示Yes
,则表示主从复制已成功搭建。
通过以上步骤,您可以在Docker中成功搭建MySQL主从复制的环境。