记录一次在CentOS8
下使用dnf
安装MySQL8
(本次配置使用8.0.21),并配置主从复制的过程
1 安装
$ sudo dnf install @mysql
2. 启动
设置开机自启并立即启动
$ sudo systemctl enable --now mysqld
3. 查看状态
$ sudo systemctl status mysqld
4. 安全配置
执行配置命令
$ sudo mysql_secure_installation
按照以下步骤设置:
- Press y|Y for Yes, any other key for No: y [说明:确认并继续设置]
- Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG: 2 [说明:密码强度]
- New password: [ENTER STRONG PASSWORD HERE] [说明:输入密码]
- Re-enter new password: RE ENTER PASSWORD HERE [说明:确认密码]
- Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : y [说明:确认使用设置的密码]
- Remove anonymous users? (Press y|Y for Yes, any other key for No) : y [说明:移除匿名用户]
- Disallow root login remotely? (Press y|Y for Yes, any other key for No) : y [说明:禁止root用户远程访问]
- Remove test database and access to it? (Press y|Y for Yes, any other key for No) : y [说明:移除测试的数据库]
- Reload privilege tables now? (Press y|Y for Yes, any other key for No) : y [说明:重新加载权限相关的表]
5. 主从复制配置
- 服务IP
主服务器: 192.168.0.15
从服务器: 192.168.0.16
- 主服务器配置
修改主服务器的配置文件 mysql-server.cnf
$ vim /etc/my.cnf.d/mysql-server.cnf
添加以下配置, server-id一般设置每个服务不一样即可,可以使用IP最后一段
server-id = 15
log-bin = /var/log/mysql/mysql-bin
log-bin
目录需要允许mysql用户访问
$ chown -R mysql:mysql /var/log/mysql
重启mysql
$ systemctl restart mysqld
进入mysql控制台后, 添加用于同步数据的数据库用户, 例如用户名是 zqyu_rpl
$ mysql -u root -p
> create user [email protected] identified by 'zqyu123456';
> grant replication slave on *.* to [email protected];
> flush privileges;
主服务器开放数据库端口给从服务器(或者直接开放3306端口)
$ firewall-cmd --permanent --add-rich-rule='
rule family="ipv4"
source address="192.168.0.16/32"
port protocol="tcp" port="3306" accept'
# 或
$ firewall-cmd --add-port=3306/tcp --permanent
# 最后
$ firewall-cmd --reload
查看并记录主服务器状态
> show master status\G;
显示如下,需要用户的属性是 File
和 Position
,作为下面从服务器配置的起始点
*************************** 1. row ***************************
File: mysql-bin.000001
Position: 853
Binlog_Do_DB:
Binlog_Ignore_DB:
Executed_Gtid_Set:
1 row in set (0.00 sec
- 从服务器配置
修改从服务器的配置文件 mysql-server.cnf
$ vim /etc/my.cnf.d/mysql-server.cnf
添加以下配置
server-id = 16
log-bin = /var/log/mysql/mysql-bin
read_only = 1
log-bin
目录需要允许mysql用户访问
$ chown -R mysql:mysql /var/log/mysql
重启mysql
$ systemctl restart mysqld
进入mysql控制台后, 配置主服务器的信息,其中 MASTER_LOG_FILE
和MASTER_LOG_POS
就是上面主服务器记录的属性值, 配置完成后执行 start slave
开启同步
$ mysql -u root -p
> CHANGE MASTER TO MASTER_HOST='192.168.0.15', MASTER_USER='zqyu_rpl', MASTER_PASSWORD='zqyu123456', MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=853;
> start slave;
查看同步状态
> show slave status\G
确认属性如下即可
Slave_IO_Running: Yes # 或者 Connecting
Slave_SQL_Running: Yes
6. 注意
如果需要修改保存位置,socket 和 socketx 默认保存位置都是 /var/lib/mysql
, 修改的话最好两个都改,例如:
[mysqld]
datadir=/home/zqyu/mysql-data
socket=/home/zqyu/mysql-data/mysql.sock
mysqlx_socket=/home/zqyu/mysql-data/mysqlx.sock
log-error=/home/zqyu/mysql-log/mysqld.log
pid-file=/run/mysqld/mysqld.pid
server-id = 5
log-bin = /home/zqyu/mysql-log/mysql-bin