实验环境: Ubuntu16.04 两台,mysql 5.7
1、主从分别执行:
apt-get update
apt-get install mysql-server #安装mysql
2、编辑配置文件mysqld.cnf
1)主:
vim /etc/mysql/mysql.conf.d/mysqld.cnf
[mysqld]
server-id = 1 //用来唯一的标识某个数据库实例的值,数值随意,但不可以重复
log_bin = /var/log/mysql/mysql-bin.log //开启binlog
注意:
bind-address = 127.0.0.1 #默认为本地地址,如果需要远程访问,则需要修改指定为从库的地址,或者直接注释掉-.-,否则后面从库同步的时候会报错,提示无法连接。
配置完成后,重启mysql 。
systemctl status mysql
systemctl restart mysql
systemctl status mysql
进入后 执行 show master status \G;显示以下信息
mysql> show master status\G;
*************************** 1. row ***************************
File: mysql-bin.000001
Position: 154
Binlog_Do_DB:
Binlog_Ignore_DB:
Executed_Gtid_Set:
1 row in set (0.00 sec)
记下file和position值,后面从库需要。
- 从
vim /etc/mysql/mysql.conf.d/mysqld.cnf
[mysqld]
server-id = 2
配置完成后,重启丛库mysql 。
systemctl restart mysql
3)在master 添加主从同步的账号,并授权
mysql> create user repl;
mysql> GRANT REPLICATION SLAVE ON . TO ‘repl’@‘从库ip地址’ IDENTIFIED BY ‘密码’; // 记得修改为自己的参数。 REPLICATION SLAVE实现从主服务器复制数据
mysql> flush privileges;
4)在slave库中执行
mysql>change master to master_host=‘主库ip地址’,master_port=3306,
master_user=‘repl’,master_password=‘密码’,master_log_file=‘mysql-bin.000001’,master_log_pos=154;
file 及pos值 即上文主库的相应值。
mysql>start slave;
mysql> show slave status \G;查看主从库状态。
Slave_IO_State: Waiting for master to send event ###
Master_Host: 192.168.1.66
Master_User: kk
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: mysql-bin.000001
Read_Master_Log_Pos: 1225
Relay_Log_File: mysql-slave-relay-bin.000002
Relay_Log_Pos: 1391
Relay_Master_Log_File: mysql-bin.000001
Slave_IO_Running: Yes ####
Slave_SQL_Running: Yes #####
Replicate_Do_DB:
Replicate_Ignore_DB:
Replicate_Do_Table:
Replicate_Ignore_Table:
Replicate_Wild_Do_Table:
Replicate_Wild_Ignore_Table:
Last_Errno: 0
Last_Error:
Skip_Counter: 0
Exec_Master_Log_Pos: 1225
Relay_Log_Space: 1604
Until_Condition: None
Until_Log_File:
Until_Log_Pos: 0
Master_SSL_Allowed: No
Master_SSL_CA_File:
如图,表示主从正常。
5)测试下。在主库建立表,数据。看从库是否同步过去。