Table of Contents
1. Prepare the Primary Server
2. Take a Backup of the Primary Data
3. Configure the Replica Server
4. Common Issues and Tips
Home Database Mysql Tutorial Setting up asynchronous primary-replica replication in MySQL

Setting up asynchronous primary-replica replication in MySQL

Jul 06, 2025 am 02:52 AM
mysql master-slave replication

To set up asynchronous master-slave replication for MySQL, follow these steps: 1. Prepare the master server, enable binary logs and set a unique server-id, create a replication user and record the current log location; 2. Use mysqldump to back up the master library data and import it to the slave server; 3. Configure the server-id and relay-log of the slave server, use the CHANGE MASTER command to connect to the master library and start the replication thread; 4. Check for common problems, such as network, permissions, data consistency and self-increase conflicts, and monitor replication delays. Follow the steps above to ensure that the configuration is completed correctly.

Setting up asynchronous primary-replica replication in MySQL

Setting up asynchronous primary-replica replication in MySQL is a common way to offload read traffic, provide redundancy, and help with backups. It's not overly complicated, but there are several important steps you need to follow carefully.

Setting up asynchronous primary-replica replication in MySQL

1. Prepare the Primary Server

Before setting up replication, make sure your primary server is configured correctly. You'll need to enable binary logging and assign a unique server ID.

Setting up asynchronous primary-replica replication in MySQL
  • Edit your MySQL configuration file (usually my.cnf or my.ini ) and add these lines under the [mysqld] section:
 server-id=1
log-bin=mysql-bin
  • Restart MySQL to apply the changes.
  • Create a dedicated replication user on the primary:
 CREATE USER 'replica_user'@'%' IDENTIFIED BY 'your_password';
GRANT REPLICATION SLAVE ON *.* TO 'replica_user'@'%';
FLUSH PRIVILEGES;

This user will be used by the replica to connect and read binary logs from the primary.

Now check the current binary log position on the primary:

Setting up asynchronous primary-replica replication in MySQL
 SHOW MASTER STATUS;

Take note of the File and Position values ​​— you'll need them later when configuring the replica.


2. Take a Backup of the Primary Data

To get the replica in sync, you need a consistent snapshot of the primary data. The easiest way is to use mysqldump .

Run this command on the primary:

 mysqldump --all-databases --master-data=2 --single-transaction -u root -p > backup.sql
  • --master-data=2 adds the binary log position as a comment in the dump file.
  • --single-transaction ensures a consistent view of the database without locking tables for long.

Transfer the backup file to the replica server using scp , rsync , or any method you prefer.

Then import it into the replica:

 mysql -u root -p < backup.sql

3. Configure the Replica Server

On the replica, edit its MySQL config and set a different server ID (it must be unique across the replication topology):

 server-id=2

Also, if you want the replica to keep a record of the replicated events, you can enable relay logs:

 relay-log=mysql-relay-bin

Restart MySQL after making changes.

Now, configure the replica to connect to the primary using the credentials and log position you recorded earlier:

 CHANGE MASTER TO
  MASTER_HOST=&#39;primary_server_ip&#39;,
  MASTER_USER=&#39;replica_user&#39;,
  MASTER_PASSWORD=&#39;your_password&#39;,
  MASTER_LOG_FILE=&#39;recorded_log_file_name&#39;,
  MASTER_LOG_POS=recorded_position;

Once that's done, start the replication threads:

 START SLAVE;

You can check the status with:

 SHOW SLAVE STATUS\G

Look for Slave_IO_Running: Yes and Slave_SQL_Running: Yes . If both are yes and there are no errors, replication is working.


4. Common Issues and Tips

Replication settings can fail for various reasons. Here are some common issues and how to avoid them:

  • Network connectivity : Make sure the replica can reach the primary on port 3306.
  • Firewall rules : Double-check that the firewall allows traffic between the servers.
  • User permissions : Confirm that the replication user has the correct privileges.
  • Data inconsistency : If the replica's data doesn't match the primary, replication might break. Use tools like pt-table-checksum to verify consistency.
  • Auto-increment conflicts : If you ever switch to multi-source or circular replication, consider adjusting auto_increment_offset and auto_increment_increment .

Also, don't forget to monitor replication lag. You can see it via SHOW SLAVE STATUS — look at the Seconds_Behind_Master field.


That's basically how you set up asynchronous replication in MySQL. It's straightforward once you've done it a few times, but always double-check each step — especially the server IDs and log positions.

The above is the detailed content of Setting up asynchronous primary-replica replication in MySQL. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Handling character sets and collations issues in MySQL Handling character sets and collations issues in MySQL Jul 08, 2025 am 02:51 AM

Character set and sorting rules issues are common when cross-platform migration or multi-person development, resulting in garbled code or inconsistent query. There are three core solutions: First, check and unify the character set of database, table, and fields to utf8mb4, view through SHOWCREATEDATABASE/TABLE, and modify it with ALTER statement; second, specify the utf8mb4 character set when the client connects, and set it in connection parameters or execute SETNAMES; third, select the sorting rules reasonably, and recommend using utf8mb4_unicode_ci to ensure the accuracy of comparison and sorting, and specify or modify it through ALTER when building the library and table.

Implementing Transactions and Understanding ACID Properties in MySQL Implementing Transactions and Understanding ACID Properties in MySQL Jul 08, 2025 am 02:50 AM

MySQL supports transaction processing, and uses the InnoDB storage engine to ensure data consistency and integrity. 1. Transactions are a set of SQL operations, either all succeed or all fail to roll back; 2. ACID attributes include atomicity, consistency, isolation and persistence; 3. The statements that manually control transactions are STARTTRANSACTION, COMMIT and ROLLBACK; 4. The four isolation levels include read not committed, read submitted, repeatable read and serialization; 5. Use transactions correctly to avoid long-term operation, turn off automatic commits, and reasonably handle locks and exceptions. Through these mechanisms, MySQL can achieve high reliability and concurrent control.

Using Common Table Expressions (CTEs) in MySQL 8 Using Common Table Expressions (CTEs) in MySQL 8 Jul 12, 2025 am 02:23 AM

CTEs are a feature introduced by MySQL8.0 to improve the readability and maintenance of complex queries. 1. CTE is a temporary result set, which is only valid in the current query, has a clear structure, and supports duplicate references; 2. Compared with subqueries, CTE is more readable, reusable and supports recursion; 3. Recursive CTE can process hierarchical data, such as organizational structure, which needs to include initial query and recursion parts; 4. Use suggestions include avoiding abuse, naming specifications, paying attention to performance and debugging methods.

Designing a Robust MySQL Database Backup Strategy Designing a Robust MySQL Database Backup Strategy Jul 08, 2025 am 02:45 AM

To design a reliable MySQL backup solution, 1. First, clarify RTO and RPO indicators, and determine the backup frequency and method based on the acceptable downtime and data loss range of the business; 2. Adopt a hybrid backup strategy, combining logical backup (such as mysqldump), physical backup (such as PerconaXtraBackup) and binary log (binlog), to achieve rapid recovery and minimum data loss; 3. Test the recovery process regularly to ensure the effectiveness of the backup and be familiar with the recovery operations; 4. Pay attention to storage security, including off-site storage, encryption protection, version retention policy and backup task monitoring.

Strategies for MySQL Query Performance Optimization Strategies for MySQL Query Performance Optimization Jul 13, 2025 am 01:45 AM

MySQL query performance optimization needs to start from the core points, including rational use of indexes, optimization of SQL statements, table structure design and partitioning strategies, and utilization of cache and monitoring tools. 1. Use indexes reasonably: Create indexes on commonly used query fields, avoid full table scanning, pay attention to the combined index order, do not add indexes in low selective fields, and avoid redundant indexes. 2. Optimize SQL queries: Avoid SELECT*, do not use functions in WHERE, reduce subquery nesting, and optimize paging query methods. 3. Table structure design and partitioning: select paradigm or anti-paradigm according to read and write scenarios, select appropriate field types, clean data regularly, and consider horizontal tables to divide tables or partition by time. 4. Utilize cache and monitoring: Use Redis cache to reduce database pressure and enable slow query

Analyzing Query Execution with MySQL EXPLAIN Analyzing Query Execution with MySQL EXPLAIN Jul 12, 2025 am 02:07 AM

MySQL's EXPLAIN is a tool used to analyze query execution plans. You can view the execution process by adding EXPLAIN before the SELECT query. 1. The main fields include id, select_type, table, type, key, Extra, etc.; 2. Efficient query needs to pay attention to type (such as const, eq_ref is the best), key (whether to use the appropriate index) and Extra (avoid Usingfilesort and Usingtemporary); 3. Common optimization suggestions: avoid using functions or blurring the leading wildcards for fields, ensure the consistent field types, reasonably set the connection field index, optimize sorting and grouping operations to improve performance and reduce capital

Optimizing complex JOIN operations in MySQL Optimizing complex JOIN operations in MySQL Jul 09, 2025 am 01:26 AM

TooptimizecomplexJOINoperationsinMySQL,followfourkeysteps:1)EnsureproperindexingonbothsidesofJOINcolumns,especiallyusingcompositeindexesformulti-columnjoinsandavoidinglargeVARCHARindexes;2)ReducedataearlybyfilteringwithWHEREclausesandlimitingselected

Working with JSON data type in MySQL Working with JSON data type in MySQL Jul 08, 2025 am 02:57 AM

MySQL supports JSON data types introduced since version 5.7 to handle structured and semi-structured data. 1. When inserting JSON data, you must use a legal format. You can use JSON_OBJECT or JSON_ARRAY functions to construct, or pass in the correct JSON string; 2. Updates should use JSON_SET, JSON_REPLACE, JSON_REMOVE to modify some fields instead of the entire replacement; 3. Query can extract fields through JSON_CONTAINS, -> operators, and note that the string value needs to be double quoted; 4. It is recommended to create a generated column and index to improve performance when using JSON type.

See all articles