# 准备工作
1、下载MySQL安装包 [传送门](https://www.mysql.com/downloads/)
2、
```
(/data/)
$ mkdir zhezhi-data;cd zhezhi-data;
$ tar -zxvf mysql-5.7.26-linux-glibc2.12-x86_64.tar.gz
$ mv mysql-5.7.26-linux-glibc2.12-x86_64 mysql
$ groupadd mysql
$ useradd -r -g mysql mysql
$ mkdir mysqldata
```
3、配置 `\data\zhezhi-data\my.cnf`
```
[mysqld]
# 不同数据库的id注意设置不一样,例如主库2077 从库2078 2079
server-id=2078
port=3310
basedir=/data/zhezhi-data/mysql
socket=/data/zhezhi-data/mysql.sock
datadir=/data/zhezhi-data/mysqldata
character_set_server=utf8
general_log_file=/data/zhezhi-data/mysql.log
log-error=/data/zhezhi-data/error.log
slow_query_log_file=/data/zhezhi-data/mysql_slow.log
pid-file=/data/zhezhi-data/mysql5722.pid
# 主库还需配置下面这项
log-bin=/data/zhezhi-data/mysql-bin.log
# 从库还需要配置下面两项
relay_log=/data/zhezhi-data/relay-log
relay_log_index=/data/zhezhi-data/relay-log.index
```
4、
```mysql
$ chown -R mysql:mysql /data/zhezhi-data
$ ./mysql/bin/mysqld --defaults-file=/data/zhezhi-data/my.cnf --initialize --user=mysql
```
5、启动MySQL服务器
`$ ./mysql/bin/mysqld_safe --defaults-file=/data/zhezhi-data/my.cnf --user=mysql`
6、连接
```
$ ./mysql/bin/mysql -uroot -p -P3310 --socket=/data/zhezhi-data/mysql.sock
$ ALTER USER 'root'@'localhost' IDENTIFIED BY '123456';
$ quit;
```
7、建立mysqlsh脚本
```
$ vi /root/zhezhi_cptmysql.sh
$ /data/zhezhi-data/mysql/bin/mysql -uroot -p123456 -P3310 --socket=/data/zhezhi-data/mysql.sock --default-character-set=utf8
$ chmod a+x /root/zhezhi_mysql.sh
```
# 配置主从复制
1、配置主库
```
$ sh /root/zhezhi_mysql.sh
$ GRANT REPLICATION SLAVE,REPLICATION CLIENT ON *.* to 'repl'@'*.*.%.%此处填从库ip' IDENTIFIED BY 'repl';
$ FLUSH PRIVILEGES;
$ show master status \G;
*************************** 1. row ***************************
File: mysql-bin.000003
Position: 1100
Binlog_Do_DB:
Binlog_Ignore_DB:
Executed_Gtid_Set:
1 row in set (0.00 sec)
```
2、配置从库
```
$ sh /root/zhezhi_mysql.sh
$ CHANGE MASTER TO master_host = '此处填主库IP',master_port = 3310,master_user='repl',master_password='repl',master_log_file='mysql-bin.000003',master_log_pos = 1100;
$ START SLAVE;
$ SHOW SLAVE STATUS \G;
```
MySQL 一主二从集群搭建实践