How to Setup MySQL Master-Master Replication
Master-Master replication allows two MySQL servers to act as both master and slave simultaneously, enabling bidirectional data synchronization. This setup enhances high availability and distributes write loads across nodes. Below is a step-by-step guide to configure MySQL Master-Master replication.
Prerequisites
- Two servers (Server A and Server B) with MySQL installed.
- Network connectivity between both servers (port
3306
open). - Identical MySQL versions on both servers (recommended).
Adjust Firewall Rules
Allow traffic between both servers:
1 | # On Server A |
Install MySQL on Both Servers
Follow the same steps as your Master-Slave guide to install MySQL and set the root password on both servers:
1 | sudo apt update |
Configure MySQL on Both Servers
Edit /etc/mysql/mysql.conf.d/mysqld.cnf
on both servers:
Server A Configuration
1 | [mysqld] |
Server B Configuration
1 | [mysqld] |
Restart MySQL on both servers:
1 | sudo systemctl restart mysql |
Create Replication Users
On both servers, create a replication user for the other server:
1 | -- On Server A: |
Initialize Data Sync
Dump the database on Server A:
1 | mysqldump -u root -p --master-data --all-databases > masterdata.sql |
Import the dump into Server B:
1 | mysql -u root -p < masterdata.sql |
Configure Replication on Both Servers
On Server A:
1 | STOP SLAVE; |
On Server B:
1 | STOP SLAVE; |
Verify Replication Status
Check replication health on both servers:
1 | SHOW SLAVE STATUS \G; |
Ensure both Slave_IO_Running
and Slave_SQL_Running
show Yes
.
Test Bidirectional Replication
Test Writes on Server A:
1 | CREATE DATABASE mm_test; |
Test Writes on Server B:
1 | USE mm_test; |
Verify Data on Both Servers:
1 | SELECT * FROM mm_test.data; |
Both servers should display:
1 | +----+---------------------+ |
Troubleshooting
Duplicate Key Errors:
Confirm
auto_increment_increment
andauto_increment_offset
are set correctly.Replication Lag:
Monitor Seconds_Behind_Master in SHOW SLAVE STATUS.
Connection Issues:
Verify firewall rules and MySQL user permissions.
Conclusion
MySQL Master-Master replication provides high availability and write scalability but requires careful conflict management. Use this setup for:
Always test conflict resolution strategies under load!