| 角色 | IP | 版本 | OS |
|---|---|---|---|
| Master | 192.168.100.231 | 5.0.19 | Linux |
| Slave | 192.168.100.234 | 5.0.18 | Linux |
編輯 /etc/my.cnf(或 /etc/init.d/mysqld 啟動腳本參數):
[mysqld]
server-id = 1
log-bin = mysql-bin
binlog-do-db = test # 僅同步 test 資料庫
重啟 Master,建立複寫專用帳號:
GRANT REPLICATION SLAVE ON *.* TO 'repl'@'192.168.100.234' IDENTIFIED BY 'repl_pass';
FLUSH PRIVILEGES;
[mysqld]
server-id = 2
master-host = 192.168.100.231
master-user = repl
master-password = repl_pass
replicate-do-db = test # 僅應用 test 資料庫的 relay log
重啟 Slave。
FLUSH TABLES WITH READ LOCK;
mysqldump -u root -p --master-data=2 test > test_master.sql
UNLOCK TABLES;test_master.sql 複製至 Slave 匯入START SLAVE;SHOW SLAVE STATUS\GSlave_IO_Running: Yes、Slave_SQL_Running: Yes、Seconds_Behind_Master: 0Table 'passport.loginuser' doesn't exist原因:Master 早期 Binlog 包含 passport 庫操作,但 Slave 只同步 test 庫,導致 Relay Log 執行失敗。
解決:在 my.cnf 加入 replicate-do-db=test 並重啟 Slave,或使用 SET GLOBAL SQL_SLAVE_SKIP_COUNTER=1 跳過錯誤事件(謹慎使用)。
Can't create database 'test'; database exists原因:人工複製資料目錄導致 Master Binlog 含 CREATE DATABASE test,Slave 重放衝突。
解決:刪除 Slave 上手工複製的 test 庫,重新 START SLAVE 讓 Binlog 自然重放建表。
Master/Slave 版本微異(5.0.19 vs 5.0.18)可能導致 Binlog 事件解析差異。建議統一版本,或升級至 5.1+ 使用 Row-based Replication(RBR)規避。
| 操作 | 指令 |
|---|---|
| 啟動/停止複寫 | START SLAVE; / STOP SLAVE; |
| 查看詳細狀態 | SHOW SLAVE STATUS\G |
| 清理舊 Binlog | PURGE MASTER LOGS TO 'mysql-bin.000004';(謹慎,確認 Slave 已應用) |
| 動態調整 Master 連線 | CHANGE MASTER TO MASTER_HOST='...', MASTER_LOG_FILE='...', MASTER_LOG_POS=...; |
sync_binlog=1、innodb_flush_log_at_trx_commit=1 保證零遺失Seconds_Behind_Master > 300 秒告警MASTER HA 切換(MHA、Orchestrator、GTID 自動故障轉移)遵循標準化部署流程、拒絕手工複製資料目錄、建立完善監控體系,是 MySQL 主從複穩定運行的三大基石。