1 主服務器上進行的操作
配置主服務器
log-bin = mysql-bin
server-id = 1
binlog_do_db = test1
binlog_do_db = test2 # 日誌記錄那些數據庫
binlog_ignore_db = mysql,performance_schema,information_schema # 日誌記錄忽略那些數據庫的
binlog_format = mixed
sync_binlog = 1 # 二進制刷盤設置,默認爲0,由文件系統決定何時刷新binlog日誌
max_binlog_size = 512M # 單個日誌文件最大
# expire_logs_day = 10 # 日誌有效期(天)
啓動mysql服務
/opt/mysql/init.d/mysql start
通過命令行登錄管理MySQL服務器
/opt/mysql/bin/mysql -uroot -p'new-password'
授權給從數據庫服務器192.168.10.131
mysql> GRANT REPLICATION SLAVE ON *.* to 'rep1'@'192.168.10.131' identified by ‘password’;
查詢主數據庫狀態
Mysql> show master status;
+------------------+----------+--------------+------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000005 | 261 | | |
+------------------+----------+--------------+------------------+
記錄下 FILE 及 Position 的值,在後面進行從服務器操作的時候需要用到。
2 配置從服務器
修改從服務器的配置文件/opt/mysql/etc/my.cnf
log_bin = mysql-bin //如果需要給其他從庫做主從的話
server_id = 2
relay_log = mysql-relay-bin //注重,開啓從服務器中繼日誌
replicate-do-db = test1
replicate-do-db = test2 //指定的數據庫名,不指定同步所有
replicate_ignore_db = mysql,performance_schema,information_schema # 日誌記錄忽略那些數據庫的
確保這個server_id 沒有被別的MySQL服務所使用。
啓動mysql服務
/opt/mysql/init.d/mysql start
通過命令行登錄管理MySQL服務器
/opt/mysql/bin/mysql -uroot -p'new-password'
執行同步SQL語句
mysql>
stop slave;
change master to
master_host='192.168.10.130',
master_user='rep1',
master_password='password',
master_log_file='mysql-bin.000005',
master_log_pos=261;
slave start;
主庫ip,如果是docker不同容器,可使用以下代碼查看容器獲得的真實ip
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_name_or_id
主從同步檢查
mysql> show slave status\G
==============================================
**************** 1. row *******************
Slave_IO_State:
Master_Host: 192.168.10.130
Master_User: rep1
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: mysql-bin.000005
Read_Master_Log_Pos: 415
Relay_Log_File: localhost-relay-bin.000008
Relay_Log_Pos: 561
Relay_Master_Log_File: mysql-bin.000005
Slave_IO_Running: YES
Slave_SQL_Running: YES
Replicate_Do_DB:
……………省略若干……………
Master_Server_Id: 1
1 row in set (0.01 sec)
==============================================
其中Slave_IO_Running 與 Slave_SQL_Running 的值都必須爲YES,才表明狀態正常。
如果主服務器已經存在應用數據,則在進行主從複製時,需要做以下處理:
(1)主數據庫進行鎖表操作,不讓數據再進行寫入動作
mysql> FLUSH TABLES WITH READ LOCK;
(2)查看主數據庫狀態
mysql> show master status;
(3)記錄下 FILE 及 Position 的值。
將主服務器的數據文件(整個/opt/mysql/data目錄)複製到從服務器,建議通過tar歸檔壓縮後再傳到從服務器解壓。
(4)取消主數據庫鎖定
mysql> UNLOCK TABLES;
注意點:
1,主從數據庫mysql端口防火牆
2,主mysql5.6,從5.6以下,要配置主服務器的 binlog_checksum =none(不建議版本不同,會出現很多錯誤);
3,sync_binlog 參數 控制數據庫的binlog刷到磁盤上,默認爲0 ,由文件系統自己控制。
可用一下代碼查看參數值:
show variables like '%sync_binlog%';
修改值:
set global sync_binlog=1;