本文演示在單機雙實例(端口 3306/3307)環境下,以「冷備份數據目錄複製」方式搭建主從複制的最簡流程。前提:主庫無寫入操作,數據目錄可直接複製。
| 角色 | 端口 | 數據目錄 | Socket |
|---|---|---|---|
| Master | 3306 | /data/mysqldata/3306 | /data/mysqldata/3306/mysql.sock |
| Slave | 3307 | /data/mysqldata/3307 | /data/mysqldata/3307/mysql.sock |
mysqladmin -umysql -p -S /data/mysqldata/3306/mysql.sock shutdown
cp -r /data/mysqldata/3306 /data/mysqldata/3307
編輯 /data/mysqldata/3306/my.cnf,在 [mysqld] 區塊添加:
server_id = 1
log_bin = ../binlog/mysql-bin
關鍵點:server_id 全局唯一(1~2³²-1),log_bin 必須啟用。
-- 啟動後無寫操作
GRANT REPLICATION SLAVE ON *.* TO 'repl'@'192.168.134.%' IDENTIFIED BY 'repl';
FLUSH PRIVILEGES;
-- 獲取 binlog 位置
SHOW MASTER STATUS;
+------------------+----------+--------------+------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000003 | 331 | | |
+------------------+----------+--------------+------------------+
編輯 /data/mysqldata/3307/my.cnf:
server_id = 2
log_bin = ../binlog/mysql-bin -- 可選,從庫不強制開啟
修改端口配置:
sed -i 's/3306/3307/g' /data/mysqldata/3307/my.cnf
關鍵步驟:刪除 auto.cnf(包含 server_uuid,複製數據目錄會衝突):
rm /data/mysqldata/3307/data/auto.cnf
# 登入 Slave 實例
mysql -umysql -p -S /data/mysqldata/3307/mysql.sock
-- 配置主庫連接信息
CHANGE MASTER TO
MASTER_HOST='192.168.134.128',
MASTER_PORT=3306,
MASTER_USER='repl',
MASTER_PASSWORD='repl',
MASTER_LOG_FILE='mysql-bin.000003',
MASTER_LOG_POS=331;
-- 啟動複制
START SLAVE;
SHOW SLAVE STATUS\G
*************************** 1. row ***************************
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
Seconds_Behind_Master: 0
-- Master 執行
USE test;
CREATE TABLE rep_test (id INT);
INSERT INTO rep_test VALUES (1), (2);
-- Slave 查詢
USE test;
SHOW TABLES;
SELECT * FROM rep_test;
| 現象 | 原因 | 解決 |
|---|---|---|
| Slave_IO_Running: No Last_IO_Error: Could not find first log file | binlog 文件名/位置錯誤 | 重新執行 SHOW MASTER STATUS 獲取正確值,CHANGE MASTER TO MASTER_LOG_FILE=..., MASTER_LOG_POS=... |
| Last_IO_Error: error connecting to master | 網絡/防火牆/賬號權限 | 檢查 GRANT ... TO 'repl'@'%'、防火牆 3306 端口、bind-address |
| Slave_SQL_Running: No Last_SQL_Error: Duplicate entry | 數據衝突/重複執行 | 跳過錯誤 SET GLOBAL sql_slave_skip_counter=1 或重新搭建 |
| server_uuid 衝突 | 未刪除 auto.cnf | 刪除 data/auto.cnf 重啟自動生成 |
MASTER_HOST 為真實 IP,確保網絡互通server_id 唯一,指向同一 Mastergtid_mode=ON,簡化故障切換Seconds_Behind_Master、Slave_*_Running 狀態