docker-compose搭建mariadb主从
1.下载镜像
docker pull mariadb
2. 安装测试
docker run --name mariadb -e MARIADB_ROOT_PASSWORD=123456 -d mariadb
3. mariadb配置文件
master.cnf
[client]
# 默认字符集
default-character-set=utf8mb4
[mysqld]
# 字符集
character-set-server = utf8mb4
collation-server = utf8mb4_general_ci
# 服务器引擎
default-storage-engine=InnoDB
# 表名小写
# lower_case_table_names=1
# bin-log
log_bin=mariadb-bin
server-id=1
log-bin=/var/log/mysql/mariadb-bin
# binlog 格式 row statement mixed
binlog_format=row
# 忽略的数据库binlog
binlog-ignore-db=mysql,information_schema
# 到期自动删除
expire_logs_day=7
slave.cnf
[client]
# 默认字符集
default-character-set=utf8mb4
[mysqld]
# 字符集
character-set-server = utf8mb4
collation-server = utf8mb4_general_ci
# 服务器引擎
default-storage-engine=InnoDB
# 表名小写
#lower_case_table_names=1
# bin-log
log_bin=mariadb-bin
server-id=11
# 同步刷新binlog
sync_binlog=1
# 从库日志更新
log_slave_updates=1
# 忽略的数据库binlog
binlog-ignore-db=mysql,information_schema
# 记录同步信息
relay-log=slave-relay-bin
# 设置只读
read_only=1
# 到期自动删除
expire_logs_day=7
4. docker-compose编写
主节点3306,从节点3307
创建网络
docker network create mariadb-network
version: '3'
services:
mariadb-master:
image: mariadb
container_name: mariadb-master
hostname: mariadb-master
restart: always
volumes:
- /srv/mariadb/master/data:/var/lib/mysql
- /srv/mariadb/master/logs:/logs
- /srv/mariadb/master/master.cnf:/etc/mysql/my.cnf
- /etc/localtime:/etc/localtime
environment:
MYSQL_ROOT_PASSWORD: 123456
ports:
- 3306:3306
command:
--lower_case_table_names=1
mariadb-slave01:
image: mariadb
container_name: mariadb-slave01
hostname: mariadb-slave01
restart: always
volumes: # 挂载
- /srv/mariadb/slave01/data:/var/lib/mysql
- /srv/mariadb/slave01/logs:/logs
- /srv/mariadb/slave01/slave.cnf:/etc/mysql/my.cnf
- /etc/localtime:/etc/localtime
environment:
MYSQL_ROOT_PASSWORD: 123456
ports:
- 3307:3306
command:
--lower_case_table_names=1
networks:
default:
external:
name: mariadb-network
yml列表用空格,用tab可能报错
5. 启动服务
docker-compose up -d
启动一直restart可以查看日志
docker logs containerName(容器名)
6. 查看主服务器是否开启log_bin
# 进入主服务器
docker exec -it mariadb-master /bin/bash
# 进入mariadb
mysql -uroot -p123456
# 查看bin_log
show variables like '%log_bin%';
7. 创建从服务器同步用户并授权
# 创建用户
create user 'slave'@'%' identified by '123456';
# 授权
grant replication slave on *.* to 'slave'@'%';
flush privileges;
8.从服务器配置
#登录从服务器
docker exec -it mariadb-slave /bin/bash
# 指定master
change master to master_host='mariadb-master',master_port=3306,\
master_user='slave',master_password='123456',master_log_file='mariadb-bin.000003',
master_log_pos=782,MASTER_SSL=1;
# 启动从服务器
start slave;
# 查看从服务器状态
show slave status \G;
9.验证
主服务器创建数据库,插入数据