操作系统:centos7.9
数据库版本:mariadb 10.5.25
虚拟机创建两台服务器,IP地址分别为1.1.1.1/1.1.1.2,其中1为主数据库,2为从数据库。
实现步骤:
1、两台虚拟机安装mariadb,步骤省略
2、配置主节点:
vim /etc/my.cnf
#添加以下内容:
[mariadb] #创建一个自定义配置组
log-bin #设置MariaDB的二进制日志
server_id=1 #服务器ID
log-basename=db-cluster-mariadb #日志基础名称
配置完成后重启服务:
systemctl restart mariadb
3、为主数据库配置复制用户:
mysql
#创建用户
MariaDB [(none)]> create user 'repl_user'@'%' identified by 'repl_userpwd';
Query OK, 0 rows affected (0.023 sec)
#为用户授权复制权限
MariaDB [(none)]> grant replication slave on *.* to 'repl_user'@'%';
Query OK, 0 rows affected (0.016 sec)
4、查看主数据库的日志位置和偏移量
MariaDB [(none)]> show master status;
+-------------------------------+----------+--------------+------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+-------------------------------+----------+--------------+------------------+
| db-cluster-mariadb-bin.000001 | 672 | | |
+-------------------------------+----------+--------------+------------------+
1 row in set (0.000 sec)
记住这个结果,后面在从节点会用到。
5、配置从节点:
vim /etc/my.cnf
#配置文件添加以下内容:
[mariadb]
log-bin
server_id=2
6、为从数据库配置主从复制:
MariaDB [(none)]> change master to
-> master_host='1.1.1.1',
-> master_user='repl_user',
-> master_password='repl_userpwd',
-> master_port=3306,
-> master_log_file='db-cluster-mariadb-bin.000001',
-> master_log_pos=672,
-> master_connect_retry=10;
Query OK, 0 rows affected (0.077 sec)
7、启动从节点,查看状态:
MariaDB [(none)]> start slave;
Query OK, 0 rows affected (0.009 sec)
MariaDB [(none)]> show slave status \G
*************************** 1. row ***************************
Slave_IO_State:
Master_Host: 1.1.1.1
Master_User: repl_user
Master_Port: 3306
Connect_Retry: 10
Master_Log_File: db-cluster-mariadb-bin.000001
Read_Master_Log_Pos: 672
Relay_Log_File: centos7-2-relay-bin.000001
Relay_Log_Pos: 4
Relay_Master_Log_File: db-cluster-mariadb-bin.000001
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
Replicate_Do_DB:
Replicate_Ignore_DB:
…………
启动主从复制之后,从节点会启动两个复制进程:
Slave_IO_Running负责从主服务器读取数据日志,存储在中继日志。
Slave_SQL_Running进程负责读取中继日志,并执行数据操作。
8、此时主从复制配置成功,主数据库的数据操作,会自动同步到从数据库。