MySQL 原生非同步主從複制實現雙機熱備。版本要求:雙邊 ≥ 3.23,Slave 版本 **≥ Master 版本**。核心機制:Master 寫 Binlog → Slave I/O 線程拉取寫 Relay Log → SQL 線程重放。
[mysqld]
server-id = 1 # 唯一,1~2^32-1
log-bin = mysql-bin # 啟用二進制日誌
binlog-do-db = db_name # 僅記錄指定庫 (可選,多庫用逗號)
binlog-ignore-db = mysql,test # 不記錄的庫 (可選)
sync_binlog = 1 # 每次提交刷盤,最安全
innodb_flush_log_at_trx_commit = 1
重啟 MySQL:systemctl restart mysqld
GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%' IDENTIFIED BY 'slavepass';
FLUSH PRIVILEGES;
5.0.2 以前版本用 GRANT FILE ON *.* ... (不建議使用舊版)。
-- 1. 鎖表 (阻寫入)
FLUSH TABLES WITH READ LOCK;
-- 2. 記錄 Binlog 座標
SHOW MASTER STATUS\G;
-- 記下 File (如 mysql-bin.000003) 和 Position (如 73)
-- 3. 備份資料 (推薦物理複製 data 目錄,或 mysqldump --master-data=2)
tar czf /backup/master_data.tar.gz /var/lib/mysql/dbname
-- 4. 解鎖
UNLOCK TABLES;
[mysqld]
server-id = 2 # 必須不同於 Master
master-host = 192.168.1.10 # Master IP
master-port = 3306
master-user = repl
master-password = slavepass
master-connect-retry = 60 # 重試間隔秒
report-host = slave-host # 可選,供 SHOW SLAVE HOSTS 顯示
relay-log = slave-relay-bin # 建議顯式指定
重啟 Slave MySQL 服務。
解壓縮備份檔到 Slave 資料目錄,或用 mysql < backup.sql 匯入。
CHANGE MASTER TO
MASTER_HOST='192.168.1.10',
MASTER_USER='repl',
MASTER_PASSWORD='slavepass',
MASTER_PORT=3306,
MASTER_LOG_FILE='mysql-bin.000003', -- 步驟 3 記錄的 File
MASTER_LOG_POS=73, -- 步驟 3 記錄的 Position
MASTER_CONNECT_RETRY=10;
START SLAVE;
SHOW SLAVE STATUS\G
-- 關鍵指標
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
Seconds_Behind_Master: 0
Master_Log_File: mysql-bin.000003
Read_Master_Log_Pos: 73
Relay_Log_File: slave-relay-bin.000002
Relay_Log_Pos: 251
兩個 Yes + Seconds_Behind_Master=0 即成功。
-- Master 端
FLUSH TABLES WITH READ LOCK;
SHOW MASTER STATUS; -- 記錄新 File/Position
UNLOCK TABLES;
-- Slave 端
STOP SLAVE;
-- Master 端 (確認 Slave 已處理完舊日誌後)
PURGE BINARY LOGS TO 'mysql-bin.000005'; -- 刪除此檔之前的所有日誌
-- 或 PURGE BINARY LOGS BEFORE '2024-01-01 00:00:00';
Seconds_Behind_Master、Slave_IO_Running、Slave_SQL_RunningCHECKSUM TABLE 或 pt-table-checksum 驗證資料一致性CHANGE MASTER TO MASTER_AUTO_POSITION=1