当前位置: 首页 > Skill >

Ops Mysql Master Slave

Ops Mysql Master Slave

1.0.2 2026.11.27 浏览:577
获取Skill文件查看使用说明
作者:陆舟许可证:
本文目录展开

MySQL Master-Slave Setup & Troubleshooting SOP

Scenario 1: Set Up MySQL Master-Slave Replication

Applicable to: Read replica setup, cross-region database acceleration, analytics query isolation.

Prerequisites

  • Master and slave running the same MySQL version (recommend 5.7 or 8.0)
  • Network connectivity between master and slave
  • Sufficient disk space on slave

Standard Steps

1. Configure master MySQL

vim /etc/my.cnf

Add the following:

[mysqld]
server-id = 1  # Must be unique
log-bin = mysql-bin
binlog_format = ROW
systemctl restart mysqld

2. Configure slave MySQL

vim /etc/my.cnf

Add the following:

[mysqld]
server-id = 2  # Must be unique, different from master
relay-log = relay-bin
read-only = 1  # Recommended for slave
systemctl restart mysqld

3. Create replication user on master

CREATE USER 'repl'@'%' IDENTIFIED BY 'password';
GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%';
FLUSH PRIVILEGES;

4. Lock tables and get binlog position

FLUSH TABLES WITH READ LOCK;
SHOW MASTER STATUS;
-- Record File and Position

Important: Do not close this session or stop MySQL before unlocking.

5. Export data from master

# Export all databases
mysqldump -u root -p --all-databases > /tmp/all_db.sql

# Export specific databases only
mysqldump -u root -p --databases db1 db2 > /tmp/db.sql

6. Record binlog info and unlock

SHOW MASTER STATUS;
-- Record mysql-bin.000001 and Position
UNLOCK TABLES;

7. Import data on slave

mysql -u root -p < /tmp/all_db.sql

8. Establish replication on slave

CHANGE MASTER TO
  MASTER_HOST = 'master_ip',
  MASTER_USER = 'repl',
  MASTER_PASSWORD = 'password',
  MASTER_LOG_FILE = 'mysql-bin.000001',
  MASTER_LOG_POS = 1234;

START SLAVE;
SHOW SLAVE STATUSG;

9. Verify replication

SHOW SLAVE STATUSG;

Check that both Slave_IO_Running and Slave_SQL_Running are Yes.

Scenario 2: Percona XtraBackup Large-Volume Migration

Applicable to: Database sizes too large for mysqldump (hundreds of GB), or when downtime must be minimized.

Why XtraBackup

  • Hot backup — no database downtime required
  • Supports parallel compression
  • Based on InnoDB crash recovery — guarantees data consistency

Environment Setup

Install XtraBackup (CentOS/RHEL 7)

yum install -y https://repo.percona.com/yum/percona-release-latest.noarch.rpm
yum install -y percona-xtrabackup-24

For Ubuntu/Debian:

apt install percona-xtrabackup-24

Database user privileges

GRANT BACKUP_ADMIN ON *.* TO 'backup_user'@'localhost';
GRANT PROCESS, RELOAD, REPLICATION CLIENT ON *.* TO 'backup_user'@'localhost';
-- Or use root if privileges are sufficient

Backup Steps

1. Full backup + compression

xtrabackup --backup 
  --target-dir=/tmp/backup_full 
  --compress 
  --compress-threads=4 
  --user=root 
  --password=password

2. Transfer to target server

scp -r /tmp/backup_full target_server:/tmp/

Restore Steps

1. Decompress (on target server)

xtrabackup --decompress --target-dir=/tmp/backup_full

2. Prepare (consistency check)

xtrabackup --prepare --target-dir=/tmp/backup_full

Important: Unprepared backups are inconsistent. Starting MySQL with unprepared files will fail.

3. Restore

⚠️ 执行前请确认:目标机器 IP 正确、数据库名正确、备份文件已 prepare 且可用。生产环境建议先快照或备份旧数据目录。

# Stop MySQL
systemctl stop mysqld

# Clear data directory
rm -rf /var/lib/mysql/*

# Copy back
xtrabackup --copy-back --target-dir=/tmp/backup_full

# Fix permissions
chown -R mysql:mysql /var/lib/mysql

# Start MySQL
systemctl start mysqld

Scenario 3: Replica Lag Investigation

Diagnostic Commands

SHOW SLAVE STATUSG;

Key metrics:

Field Meaning
Slave_IO_Running IO thread status
Slave_SQL_Running SQL thread status
Seconds_Behind_Master Lag in seconds (0 = no lag)
Read_Master_Log_Pos Master binlog position read
Relay_Log_Space Total relay log size

Common Causes

Cause Symptom Resolution
Slave machine underpowered High CPU/IO Upgrade slave hardware
Large transaction blocking SQL thread stuck Split large transactions
Network latency IO thread slow Check master-slave network
Replication stopped SQL thread Stopped START SLAVE to retry

Cross-Cloud Database Acceleration

Applicable when: Remote servers need to access a central database with high latency (e.g., overseas servers accessing a domestic database).

Remote server → Cloud Global Accelerator → Domestic source ECS

Configuration steps:

  1. Create a global acceleration instance in your cloud provider's console
  2. Configure acceleration region (remote) and source IP (domestic MySQL)
  3. Obtain the accelerated IP
  4. Configure security group on source server to allow the accelerator's backend nodes (note: IP group may be dynamic)
  5. Test: telnet accelerated_ip 3306

Scenario 4: MySQL Memory Usage Investigation

Applicable to: Self-managed MySQL with high memory usage causing performance degradation.

Investigation Steps

1. Confirm MySQL memory usage

ps -eo pid,rss,vsz,comm | grep mysql
top -b -n 1 | grep mysql

2. Buffer Pool usage by database

SELECT
    SUBSTRING_INDEX(table_name, '/', 1) AS db,
    COUNT(*) * 16 / 1024 AS size_mb
FROM information_schema.innodb_buffer_page_lru
WHERE table_name IS NOT NULL
GROUP BY db
ORDER BY size_mb DESC
LIMIT 20;

3. Buffer Pool total usage

SELECT COUNT(*) * 16 / 1024 AS total_mb
FROM information_schema.innodb_buffer_page_lru;

4. MySQL memory distribution (non-buffer pool)

SELECT
    event_name,
    CURRENT_NUMBER_OF_BYTES_USED / 1024 / 1024 AS current_mb,
    HIGH_NUMBER_OF_BYTES_USED / 1024 / 1024 AS high_mb
FROM performance_schema.memory_summary_global_by_event_name
ORDER BY CURRENT_NUMBER_OF_BYTES_USED DESC
LIMIT 20;

5. Active connections

SHOW STATUS LIKE 'Threads_connected';
SHOW STATUS LIKE 'Max_used_connections';

6. Identify high-memory tables

SELECT
    table_schema AS 'db',
    table_name AS 'table',
    ROUND(data_length / 1024 / 1024, 2) AS 'data_size_mb',
    ROUND(index_length / 1024 / 1024, 2) AS 'index_size_mb'
FROM information_schema.tables
WHERE table_schema NOT IN ('mysql', 'information_schema', 'performance_schema')
ORDER BY data_length DESC
LIMIT 20;

Common Findings

Scenario Indicator Recommendation
Single db high buffer pool Normal, frequently accessed Acceptable
Buffer pool near limit innodb_buffer_pool_size too large Reduce or upgrade memory
Non-buffer pool abnormal Temp tables / large sorts / big queries Optimize SQL
Many connections Connection pool leak or unclosed connections Check application connection pool

Scenario 5: Cross-Server Database Migration (Comprehensive)

Applicable to: Game server migration, server upgrades, regional data transfers.

Standard Flow

1. Export cross-server data
         ↓
2. Upload to target machine
         ↓
3. Create database and import data
         ↓
4. Migrate game/service directory
         ↓
5. Modify configuration files
         ↓
6. Update ops/management database records
         ↓
7. Batch update related service configurations
         ↓
8. Restart service

Key Checkpoints

Step Check
Data export Stop writes, lock tables or shut down service
Data transfer Verify md5sum
Data import Check error logs
Config update Confirm IP, port, database name
Database update ops_server table, management config
Service restart Verify process and port

Command Cheatsheet

# Check replica status
SHOW SLAVE STATUSG;

# Check master binlog position
SHOW MASTER STATUS;

# Stop/start replica
STOP SLAVE;
START SLAVE;

# Reset replica configuration
RESET SLAVE ALL;

# Check connections
SHOW STATUS LIKE 'Threads_connected';

# Check max connections
SHOW VARIABLES LIKE 'max_connections';

# MySQL buffer pool usage by db
SELECT
    SUBSTRING_INDEX(table_name, '/', 1) AS db,
    COUNT(*) * 16 / 1024 AS size_mb
FROM information_schema.innodb_buffer_page_lru
WHERE table_name IS NOT NULL
GROUP BY db;

# XtraBackup backup
xtrabackup --backup --target-dir=/tmp/backup --user=root --password=password

# XtraBackup restore
xtrabackup --prepare --target-dir=/tmp/backup
xtrabackup --copy-back --target-dir=/tmp/backup

Notes

  1. server-id must be unique — master and slave cannot have the same value
  2. Set read-only=1 on slave — prevents accidental writes
  3. Use XtraBackup for large volumes — mysqldump may fail or take too long
  4. High replica lag — check slave machine performance and network first
  5. Always confirm IP, port, database name before migration — wrong values will break connectivity
  6. Cross-cloud migration has network latency — consider using a cloud global acceleration service

推荐文章

更多
PHP时间戳与日期字符串相互转换方法详解

本文介绍PHP中时间数值(Unix时间戳)与日期字符串之间的相互转换方法。通过strtotime和date函数,实现将当前时间、指定日期转换为时间戳,以及将时间戳格式化为可读的日期时间字符串,并提供相关在线计算工具推荐。

2025.11.30 1,031
PHP日期转时间戳时区偏差怎么解决

在 PHP 中将日期字符串转换为时间戳时,若未显式指定时区,默认使用脚本配置的 date.timezone 或系统时区。当服务器时区与业务逻辑预期(如 UTC )不一致时,会产生偏差。解决核心是确保输入字符串携带明确时区信息,或在转换前统一设置时区上下文。

2026.10.24 1,029
PHP跨域配置:怎么安全地允许指定域名而非使用通配符

在 PHP 中安全地允许指定域名跨域,核心是解析请求头中的 Origin ,验证其是否在白名单内,然后动态设置 Access-Control-Allow-Origin 响应头。不要使用通配符 * ,也不要硬编码单一域名。

2025.03.29 1,017
JavaScript中利用replace结合正则实现replaceAll效果

JavaScript原生仅支持replace()进行单次或全局替换,缺乏类似Java的replaceAll()便捷方法。本文总结四种在JS中实现全量替换的方案:使用带g标志的正则、带gm标志的正则、扩展String原型以及split后join。通过对比代码示例,展示各方法的实现细节与适用场景,帮助开发者根据需求选择最优解。

2025.04.29 1,014
OpenAI的Jalapeno芯片未落地,教你分辨300兆瓦算力消息

OpenAI计划在SB Energy租赁的数据中心部署约300兆瓦自研Jalapeno推理芯片,但目前双方仍处于洽谈阶段,交易细节与上线时间表均未公布。本文带你按报道原文核实项目所处阶段,厘清芯片发布、电力功率与实际推理算力的边界,并将融资意向与签约、开工、投运节点分开追踪,避免误将规划容量计入现有算力。

2026.12.02 1,011
PHP实现基础文件上传:HTML表单与$_FILES处理流程

在 HTML 表单中设置 enctype="multipart/form-data" ,并在 PHP 后端通过 $_FILES 数组接收文件,调用 move_uploaded_file() 将临时文件移动到目标目录即可完成上传。

2026.09.07 1,011
Skill 文件
  • SKILL.md
    • MySQL Master-Slave Setup & Troubleshooting SOP
    • Scenario 1: Set Up MySQL Master-Slave Replication
      • Prerequisites
      • Standard Steps
    • Scenario 2: Percona XtraBackup Large-Volume Migration
      • Why XtraBackup
      • Environment Setup
      • Backup Steps
      • Restore Steps
    • Scenario 3: Replica Lag Investigation
      • Diagnostic Commands
      • Common Causes
      • Cross-Cloud Database Acceleration
    • Scenario 4: MySQL Memory Usage Investigation
      • Investigation Steps
      • Common Findings
    • Scenario 5: Cross-Server Database Migration (Comprehensive)
      • Standard Flow
      • Key Checkpoints
    • Command Cheatsheet
    • Notes
  • 项目或源文件

相关 Skill

更多
Volcengine RDS Mysql Volcengine RDS Mysql 使用火山引擎 RDS MySQL MCP Server,帮助用户完成 RDS MySQL 相关的实例管理、数据库操作、账号管理和运维任务,可直接调用 uv run ./scripts/call_rds_mysql.py 脚本获取实时结果。
Aliyun Adb Mysql Aliyun Adb Mysql 用于通过 OpenAPI/SDK 管理阿里云 AnalyticDB for MySQL (ADB),包括资源生命周期及配置操作。
MYSQL QUERY MYSQL QUERY 自动管理SSH隧道,查询项目数据库。适用于在已配置的数据库上执行SQL查询,尤其是需要通过SSH访问的数据库。
MySQL to PostgreSQL Migration MySQL to PostgreSQL Migration 在将项目数据库层从MySQL迁移到PostgreSQL时使用此技能。覆盖SQL方言转换(MyBatis XML/原始SQL)和ORM配置等...
在使用 Skeema 进行危险的数据库部署之前,将 MySQL 架构变更作为文件系统管理的 SQL 进行差异对比和审查 在使用 Skeema 进行危险的数据库部署之前,将 MySQL 架构变更作为文件系统管理的 SQL 进行差异对比和审查 将实时MySQL模式拉取到文件中,检查差异,并使用可重复的工作流程推送已审核的更改。