ubuntu22.04搭建MySQL8.0.35主从复制

一,更新源:

  • 备份源文件

sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak

  • 更改为清华大学源

sudo vim /etc/apt/sources.list

# 默认注释了源码镜像以提高 apt update 速度,如有需要可自行取消注释
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ focal main restricted universe multiverse
# deb-src https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ focal main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ focal-updates main restricted universe multiverse
# deb-src https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ focal-updates main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ focal-backports main restricted universe multiverse
# deb-src https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ focal-backports main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ focal-security main restricted universe multiverse
# deb-src https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ focal-security main restricted universe multiverse
  • 更新所有可用系统更新

sudo apt update && sudo apt full-upgrade

  • 删除不再使用的软件

sudo apt autoremove

 二,安装MySQL

  • 更新软件包

sudo apt update

sudo apt upgrade

  •  使用命令下载MySQL

sudo apt install mysql-server

  •  安装完成后,启动 MySQL 服务:

 sudo systemctl start mysql

  •  设置MySQL开机自启动

sudo systemctl enable mysql

  •  安装完成查看MySQL版本

mysql -V

 

  •  连接MySQL(首次登录无需密码,直接回车即可登录)

 mysql -u root -p

  •  设置MySQL密码

alter user 'root'@'localhost' identified by 'password';

  •  授权远程登录:

CREATE USER 'root'@'%' IDENTIFIED BY '123456';

GRANT ALL PRIVILEGES ON . TO 'root'@'%';

FLUSH PRIVILEGES;

  •  修改/etc/mysql/mysql.conf.d/mysqld.cnf

 bind-address= 0.0.0.0

三,修改配置

  • 主库(mysql配置默认路径:/etc/mysql/mysql.conf.d/mysqld.cnf)
[mysqld]
server-id=100
# 开启日志路径(必须)
log_bin=/var/log/mysql/mysql-bin.log
# binlog实效日期,默认30天
binlog_expire_logs_seconds=2592000
# binlog日志文件大小 (请注意是 max_binlog_size,不是 max_binglog_size)
max_binlog_size=100M
# binlog过期清理时间
expire_logs_days=7
# binlog每个日志文件大小
max_binlog_size=100M
# binlog缓存大小
binlog_cache_size=4M
# 最大binlog缓存大小
max_binlog_cache_size=512M
# 需要同步的数据库名称,可定义多个相同属性
binlog_do_db=testcz
# 同步需要过滤的数据库名称,可定义多个相同属性
binlog_ignore_db=exclude_database_name
binlog_format=ROW
  • 从库 
# 服务器唯一ID(必须)
server-id=101
replicate-do-db=testcz
replicate-ignore-db=mysql
  • 重启主从两个MySQL 

 systemctl restart mysql

四,配置主从

  • 查看主库状态

mysql -u root -p
mysql> show master status;
# 记住查询结果的列(file,position),从库连接用到

 

  •  主库连接配置
mysql -u root -p
# 创建用户slave 密码123456 并授权
mysql>CREATE USER 'slave'@'%' IDENTIFIED WITH 'mysql_native_password' BY '123456';
mysql>GRANT REPLICATION SLAVE ON *.* TO 'slave'@'%';  
  •  从库连接配置
mysql -u root -p;
mysql> change master to  master_host = '172.16.66.66',  # 主机的IP地址  
master_user = 'slave',      # 之前在主机上创建的用户  
master_password = '123456',    # 主机上创建的新用户的密码
master_log_file = 'mysql-bin.000004', # 之前记录的二进制日志文件的名称    
master_log_pos = 157;     # 之前记录的二进制日志文件的位置
mysql>start slave; #开启从机的复制
# 查看是否启用成功 (如下图)
mysql>show  slave statusG

到此结束!