docker搭建mysql主从集群

docker mysql 主从复制

docker-compose.yml

version: "3"
services:
  master:
    image: mysql:8.0
    container_name: master
    restart: always
    volumes:
      - ./master/conf:/etc/mysql/conf.d:ro
      - ./master/data:/var/lib/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=123456
    ports:
      - 3316:3316
  slave:
    image: mysql:8.0
    container_name: slave
    restart: always
    volumes:
      - ./slave/conf:/etc/mysql/conf.d:ro
      - ./slave/data:/var/lib/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=123456
    ports:
      - 3317:3317
docker-compose up -d 

主库 master.conf

[mysqld]

bind_address = 0.0.0.0
## read-only=0 ## 1可读写0可读
server-id = 23 #IP 需要唯一
read-only=0 # 可读写
log_bin = mysql-bin # bin log
port = 3316
expire_logs_days = 20 #过期时间

max_binlog_size = 200M # 日志大小

binlog_do_db = test # 需要备份的库

# 不需要备份的库
replicate-ignore-db=mysql
replicate-ignore-db=sys
replicate-ignore-db=information_schema
replicate-ignore-db=performance_schema

从库 slave.cnf

[mysqld]

bind_address = 0.0.0.0
## read-only=0 ## 1可读写0可读
server-id = 230 #IP 需要唯一
read-only=1 # 可读
log_bin = mysql-bin # bin log
port = 3317
expire_logs_days = 20 #过期时间

max_binlog_size = 200M # 日志大小

binlog_do_db = test # 需要备份的库

# 不需要备份的库
replicate-ignore-db=mysql
replicate-ignore-db=sys
replicate-ignore-db=information_schema
replicate-ignore-db=performance_schema

由上述 master.cnf 和 slave.cnf 配置文件中可知,两者的区别主要在于 server_id 和 read-only 值不同
server_id 标识服务实例,master 和 slave 值需要保证唯一
read-only 中值为 0 表示支持可读写、1 的话表明仅支持可读

主库

创建用户

create user 'slave'@'%' identified by '123456';
GRANT REPLICATION slave ON *.* to 'slave'@'%';
## 修改 Authentication requires secure connection.
SELECT plugin FROM `user` where user = 'slave';
ALTER USER 'slave'@'%' IDENTIFIED WITH mysql_native_password BY '123456';

查看状态,记住File、Position的值,在Slave中将用到

show master status \G;

image-20210430143129012

从库

  • 连接到主库
change master to master_host='192.168.0.254',master_user='slave',master_password='123456',master_log_file='mysql-bin.000003',master_log_pos=692,master_port=3316;
  • 启动从库同步
start slave;
  • 查看状态
show slave status\G;

image-20210430150451540

slave_io_runing与slave_sql_running :为yes说明正常工作

测试

  • 主库
use test;
create  table test(id int primary key auto_increment,username varchar(100) default '');
show tables;
insert into test(username)values("a");
select * from test;

image-20210430151019946

  • 从库
use test;
show tables;
select * from test;

image-20210430151235736

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值