基於 CentOS 6.5 + Percona Server 5.6.20,記錄雙節點主從搭建全過程,含防火牆阻斷、權限缺失、只讀配置失效等真實坑點及解決,附災難恢復 SOP。
[mysqld] server-id=10 log-bin=mysql-bin binlog_format=ROW binlog-ignore-db=mysql,information_schema,performance_schema replicate-do-db=reptest gtid-mode=on enforce-gtid-consistency=on log-slave-updates=1 sync-master-info=1
[mysqld] server-id=20 relay_log=mysql-relay-bin read_only=1 # 以下舊式配置在 5.6+ GTID 模式下不生效,由 CHANGE MASTER TO 指定 # master-host=192.168.18.66 # master-user=repl # master-password=123
GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%' IDENTIFIED BY '123456'; FLUSH PRIVILEGES;
FLUSH TABLES WITH READ LOCK; SHOW MASTER STATUS\G; -- 記錄 File、Position mysqldump -uroot -p reptest --triggers --routines --events > /home/zxw/master_reptest.sql UNLOCK TABLES;
CREATE DATABASE reptest; mysql -uroot -p reptest < /home/zxw/master_reptest.sql
CHANGE MASTER TO
MASTER_HOST='192.168.18.66',
MASTER_PORT=3306,
MASTER_USER='repl',
MASTER_PASSWORD='123456',
MASTER_LOG_FILE='mysql-bin.000002',
MASTER_LOG_POS=401,
MASTER_AUTO_POSITION=1; -- GTID 模式核心參數
START SLAVE;
SHOW SLAVE STATUS\G; -- 關鍵指標: Slave_IO_Running: Yes Slave_SQL_Running: Yes Seconds_Behind_Master: 0 Auto_Position: 1 Retrieved_Gtid_Set: ... Executed_Gtid_Set: ...
Last_IO_Error: error connecting to master 'repl@192.168.18.66:3306' - retry-time: 60 retries: 1 Last_IO_Errno: 2003
mysql -h 192.168.18.66 -u repl -p 連不上,主庫 iptables -L 無 3306 規則。/etc/sysconfig/iptables 添加 -A INPUT -m state --state NEW -m tcp -p tcp --dport 3306 -j ACCEPT,service iptables restart。iptables -L 出現 ACCEPT tcp -- anywhere anywhere state NEW tcp dpt:mysql,從庫 START SLAVE 即正常。Access denied for user 'repl'@'...'。REPLICATION SLAVE。GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%' IDENTIFIED BY '123456';。read_only=1 重啟後,直接連從庫 INSERT 成功。read_only **不限制 SUPER 權限用戶**(root 默認有 SUPER)。super_read_only=1 (5.7.8+) 連 SUPER 也限制。STOP SLAVE;STOP SLAVE;GRANT REPLICATION SLAVE ON *.* TO 'repl'@'從庫IP' IDENTIFIED BY '123456';| 指標 | 正常值 | 告警閾值 |
|---|---|---|
| Slave_IO_Running | Yes | ≠ Yes |
| Slave_SQL_Running | Yes | ≠ Yes |
| Seconds_Behind_Master | 0~秒級 | > 300s (5分鐘) |
| Executed_Gtid_Set | 持續增長 | 停滯 |
| Relay_Log_Space | 穩定 | 持續暴增 (磁盤滿風險) |
**GTID + MASTER_AUTO_POSITION=1** 是 5.6+ 主從搭建的標準姿勢,告別手動算 binlog 位點。真實環境三大殺手:**防火牆、權限缺失、read_only 對 SUPER 不生效**。建立「部署清單、驗證清單、監控儀表板、災難演練腳本」四件套,才能讓主從集群在生產環境穩定跑滿 SLA。