Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> 電腦軟體教學 >> 伺服器技術 >> 關於伺服器

MySQL 主從複寫完整設定教學:從環境準備到驗證同步

編輯:關於伺服器

本文記錄 MySQL 5.0.16 在 RedHat 9 上建立主從複寫的完整實作流程,涵蓋版本確認、帳號授權、資料快照、二進制日誌座標記錄、配置檔調整、從伺服器啟動與同步驗證等關鍵步驟,供參考實作。

實驗環境

角色主機名IPOSMySQL 版本
Masterdbmaster192.168.0.111RedHat 95.0.16
Slavedbslave192.168.0.100RedHat 95.0.16

關鍵步驟總覽

1. 確認版本相容性

mysql -V

建議 Master/Slave 使用相同版本;若無法滿足,Master 版本不得高於 Slave,以免 Binlog 格式不相容。

2. 建立複寫專用帳號(Master 端)

GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%.mydomain.com' IDENTIFIED BY 'slavepass';

若需支援 LOAD TABLE FROM MASTER,須額外授予 FILE, SELECT 權限。本實驗為簡化直接使用 root 帳號(生產環境請勿照做)。

3. 鎖定資料表並建立快照

mysql> FLUSH TABLES WITH READ LOCK;
mysql> SHOW MASTER STATUS;

記錄 File 與 Position 值(如 mysql-bin.000045, 947),後續從伺服器設定需用到。
另開 SSH 視窗打包資料目錄:

shell> tar -cvf /tmp/mysql-snapshot.tar .
shell> scp /tmp/mysql-snapshot.tar 192.168.0.100:/tmp/

Slave 端解壓:

shell> tar -xvf /tmp/mysql-snapshot.tar

完成後 Master 執行 UNLOCK TABLES; 釋放鎖定。

4. 修改 Master my.cnf 啟用 Binlog

[mysqld]
log-bin=mysql-bin
server-id=1

若選項不存在請新增並重啟服務;未啟用 Binlog 無法作為複寫主機。

5. 設定 Slave my.cnf

[mysqld]
server-id=2  # 必須唯一且不同於 Master
# 註解掉 Master 相關選項
# log-bin=mysql-bin
# server-id=1

多從伺服器時,server-id 依序遞增(3, 4...)。

6. 啟動 Slave 並設定複寫座標

mysql> CHANGE MASTER TO
    MASTER_HOST='192.168.0.111',
    MASTER_USER='root',
    MASTER_PASSWORD='xxx',
    MASTER_LOG_FILE='mysql-bin.000045',
    MASTER_LOG_POS=947;
mysql> START SLAVE;

7. 驗證同步狀態

mysql> SHOW SLAVE STATUS\G

關鍵指標均為 Yes 即代表複寫正常:

  • Slave_IO_Running: Yes
  • Slave_SQL_Running: Yes
  • Seconds_Behind_Master: 0

執行 SHOW PROCESSLIST\G 可見兩條 system user 連線分別處於 Waiting for master to send event 與 Has read all relay log 狀態。

測試與說明

在 Master 執行 UPDATE 語句,Slave 即刻同步更新。複寫架構下,所有寫入操作必須在 Master 執行,Slave 僅供查詢(讀寫分離),確保資料一致性。

Copyright © Windows教程網 All Rights Reserved