Master (192.168.1.1) --binlog--> Slave (192.168.1.2)
server-id=1 server-id=2
log-bin=mysql-bin read-only=1 (建議)
binlog-do-db=powerdns replicate-do-db=powerdns (可選)
/etc/my.cnf[mysqld]
server-id = 1
log-bin = mysql-bin
binlog-do-db = powerdns # 只同步指定庫,省資源
binlog-ignore-db = mysql # 忽略系統庫
expire_logs_days = 7 # 自動清理舊 binlog
max_binlog_size = 100M
GRANT REPLICATION SLAVE ON *.* TO 'repl_user'@'192.168.1.%' IDENTIFIED BY 'StrongPass123!';
FLUSH PRIVILEGES;
FLUSH TABLES WITH READ LOCK; -- 短暫鎖表,確保一致性座標
SHOW MASTER STATUS;
+------------------+----------+--------------+------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000004 | 106 | powerdns | mysql |
+------------------+----------+--------------+------------------+
UNLOCK TABLES;
記住 File 與 Position,後續 Slave 配置需用到。
/etc/my.cnf[mysqld]
server-id = 2
log-bin = mysql-bin # 從庫也開 binlog,支援級聯/備份
relay-log = relay-bin
read-only = 1 # 防止誤寫入
replicate-do-db = powerdns # 可選,與 Master 對應
CHANGE MASTER TO
MASTER_HOST='192.168.1.1',
MASTER_USER='repl_user',
MASTER_PASSWORD='StrongPass123!',
MASTER_PORT=3306,
MASTER_LOG_FILE='mysql-bin.000004',
MASTER_LOG_POS=106;
START SLAVE;
SHOW SLAVE STATUS\G
*************************** 1. row ***************************
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
Seconds_Behind_Master: 0
Last_IO_Error:
Last_SQL_Error:
...
關鍵指標:Slave_IO_Running=Yes(I/O 線程連接正常)、Slave_SQL_Running=Yes(SQL 線程執行正常)、Seconds_Behind_Master=0(無延遲)。
| 現象 | 原因 | 處理 |
|---|---|---|
| IO_Running=No, Last_IO_Error: Access denied | 帳號/密碼/IP 錯誤 | 核對 GRANT 主機、密碼、防火牆 |
| IO_Running=No, Last_IO_Error: timeout | 網路不通/防火牆 | telnet master 3306、安全組放行 |
| SQL_Running=No, Last_SQL_Error: Duplicate entry | 主鍵衝突/手動寫入從庫 | 跳過錯誤 SET GLOBAL sql_slave_skip_counter=1; START SLAVE; 或重建從庫 |
| Seconds_Behind_Master 持續增長 | 從庫寫入慢/大事務/硬體瓶頸 | 優化從庫索引、參數、升級硬體、並行複製 |
Slave_IO_Running/Slave_SQL_Running/Seconds_Behind_Master,異常即時告警。CHECKSUM TABLE 或 pt-table-checksum 驗證主從資料一致性。xtrabackup 或 mysqldump --single-transaction --master-data=2),不影響主庫效能。CHANGE MASTER TO MASTER_AUTO_POSITION=1,無需手動指定 File/Position。主從同步核心四步:**Master 開 binlog + 建帳號 → 記錄座標 → Slave 設定 CHANGE MASTER → START SLAVE 驗證**。生產環境務必加上 read-only、GTID、半同步複制、監控告警 四大保障。