| 角色 | IP | Hostname |
|---|---|---|
| Master | 192.168.137.12 | s3-db-master |
| Slave | 192.168.137.13 | s3-db-slave |
# 兩台機器同步執行
sudo apt-get update && sudo apt-get upgrade -y
sudo apt-get install mysql-server -y
# 設置 root 密碼,並允許遠程訪問(註釋 bind-address 或設 0.0.0.0)
編輯 /etc/mysql/my.cnf:
[client]
default-character-set = utf8mb4
[mysqld]
default-character-set = utf8mb4
init_connect = 'SET NAMES utf8mb4;'
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci
重啟:sudo systemctl restart mysql
[mysqld]
server-id = 1
log-bin = mysql-bin
binlog-do-db = s3
binlog-format = ROW # 推薦 ROW 格式,避免不一致
sync_binlog = 1 # 最高持久化
innodb_flush_log_at_trx_commit = 1
重啟 MySQL。
mysql -u root -p
CREATE DATABASE s3 CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
GRANT REPLICATION SLAVE ON *.* TO 'sync'@'%' IDENTIFIED BY '12345';
FLUSH PRIVILEGES;
# 記錄當前 Binlog 位置
SHOW MASTER STATUS;
+------------------+----------+--------------+------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000007 | 106 | s3 | |
+------------------+----------+--------------+------------------+
[mysqld]
server-id = 2
read-only = 1 # 防止誤寫入
master-connect-retry = 60
replicate-do-db = s3
relay-log = s3-relay-bin # 固定 relay log 名稱
relay-log-index = s3-relay-bin.index
重啟 MySQL,並建立同名資料庫:
mysql -u root -p -e "CREATE DATABASE s3 CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
mysql -u root -p
CHANGE MASTER TO
MASTER_HOST='192.168.137.12',
MASTER_USER='sync',
MASTER_PASSWORD='12345',
MASTER_LOG_FILE='mysql-bin.000007',
MASTER_LOG_POS=106;
START SLAVE;
SHOW SLAVE STATUS\G
*************************** 1. row ***************************
Slave_IO_State: Waiting for master to send event
Master_Host: 192.168.137.12
Master_User: sync
Master_Port: 3306
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
Seconds_Behind_Master: 0
...
Replicate_Do_DB: s3
成功標誌:Slave_IO_Running: Yes 且 Slave_SQL_Running: Yes。
# Master
mysql -u root -p s3 -e "CREATE TABLE test_sync (id INT PRIMARY KEY, name VARCHAR(20)); INSERT INTO test_sync VALUES (1, 'hello');"
# Slave
mysql -u root -p s3 -e "SELECT * FROM test_sync;"
+----+-------+
| id | name |
+----+-------+
| 1 | hello |
+----+-------+
cat /var/log/mysql/error.logSHOW SLAVE STATUS\G 關注 Last_IO_Error、Last_SQL_ErrorSTOP SLAVE; SET GLOBAL sql_slave_skip_counter=1; START SLAVE;FLUSH TABLES WITH READ LOCK → mysqldump --master-data=2 → Slave 匯入 → CHANGE MASTER TO ...gtid_mode=ON、enforce_gtid_consistency=ONSeconds_Behind_Master > 300 告警