MySQL 的 Master-Slave Replication (同步) 是當 Master 資料庫有變動時, 自動同步到 Slave 資料庫。由於 MariaDB 在 RHEL/CentOS 7 開始已經成為預設資料庫, 而且可以完全取代 MySQL, 所以以下也會以 MariaDB 進行設定, 但同樣方法在 MySQL 一樣可以的。
假設已經有兩台 MySQL 伺服器, 以下兩部份分別是 Master 及 Slave 的設定。
Master
開啟 /etc/my.cnf 進行設定, 在 [mysqld] 區塊改成以下這樣, 其中 bind-address 要改成 Master 的 ip; datadir 是資料目錄:
1 2 3 4 5 6 7 8 9 |
[mysqld] bind-address=192.168.1.100 server-id=1 binlog-ignore-db = "mysql" binlog-format = mixed log-bin=mysql-bin datadir=/var/lib/mysql innodb_flush_log_at_trx_commit=1 sync_binlog=1 |
修改後儲存檔案, 重新啟動 MySQL:
接著用 root 登入 MySQL, 建立一個用作同步的帳號, 以下會建立帳號 replication, 密碼是 password, Slave 的 ip 是 192.168.1.101:
1 2 3 4 5 |
MariaDB> CREATE USER replication@192.168.1.101; MariaDB> GRANT REPLICATION SLAVE ON *.* TO replication@192.168.1.101 IDENTIFIED BY 'password'; MariaDB> flush privileges; MariaDB> SHOW MASTER STATUS; MariaDB> exit; |
然後要用 mysqldump 匯出資料庫的 .sql 檔, 要放到 Slave 匯入:
Slave 設定
開啟 /etc/my.cnf 修改設定, 加入以下內容到 [mysqld] 區塊:
1 2 3 4 5 6 7 |
[mysqld] server-id=2 binlog-format=mixed log_bin=mysql-bin relay-log=mysql-relay-bin log-slave-updates=1 read-only=1 |
修改後儲存檔案, 重新啟動 MySQL:
用 root 登入 MySQL, 建立資料庫:
1 2 |
MariaDB> create database database-name; MariaDB> exit; |
將在 Master 用 mysqldump 建立的 masterdatabase.sql 匯入:
匯入資料後, 再次用 root 登入 MySQL, 執行以下 SQL 指令, 以下的 MASTER_HOST 改為 Master 的 ip, 而 MASTER_LOG_FILE 及 MASTER_LOG_POS 是在 Master 上在 MySQL 執行 “SHOW MASTER STATUS;” 的結果:
1 2 3 |
MariaDB> CHANGE MASTER TO MASTER_HOST='192.168.1.100',MASTER_USER='replication',MASTER_PASSWORD='password', MASTER_LOG_FILE='mariadb-bin.000001', MASTER_LOG_POS=500; MariaDB> START SLAVE; MariaDB> SHOW SLAVE STATUS \G; |
現在 Slave 已經可以同步, 要查詢 Slave 的狀態, 可以登入 MySQL 用以下指令檢查:
1 2 |
MariaDB> START SLAVE; MariaDB> SHOW SLAVE STATUS \G; |