Step 1: Configure the Master Server
-
Edit the MySQL configuration file (
my.cnformy.ini, depending on the operating system):- Enable binary logging:
ini
[mysqld] log-bin=mysql-bin - Set a unique server ID:
ini
server-id=1
- Enable binary logging:
-
Restart the MySQL service to apply the configuration.
-
Create a user with replication privileges:
sqlCREATE USER 'replicator'@'%' IDENTIFIED BY 'password'; GRANT REPLICATION SLAVE ON *.* TO 'replicator'@'%'; FLUSH PRIVILEGES; -
Record the current binary log position:
sqlSHOW MASTER STATUS;Note down the values of
FileandPosition, which will be used later when configuring the slave server.
Step 2: Configure the Slave Server
-
Edit the MySQL configuration file for the slave server:
- Set a unique server ID (different from the master server):
ini
server-id=2
- Set a unique server ID (different from the master server):
-
Restart the MySQL service to apply the configuration.
-
Configure the master server information on the slave server:
sqlCHANGE MASTER TO MASTER_HOST='master_ip_address', MASTER_USER='replicator', MASTER_PASSWORD='password', MASTER_LOG_FILE='recorded_log_file_name', MASTER_LOG_POS=recorded_log_position; -
Start the replication process:
sqlSTART SLAVE; -
Check the replication status:
sqlSHOW SLAVE STATUS\G;Confirm that both
Slave_IO_RunningandSlave_SQL_RunningareYes.
Example Application
Suppose you have an e-commerce website where the database experiences high traffic during peak hours. By setting up read replication on multiple slave servers, you can offload read operations from the master database, thereby reducing the load on the master server and improving query response times and overall system performance.
Other Considerations
- Ensure that the time settings on the master and slave servers are synchronized.
- Regularly monitor replication health to promptly address potential delays or errors.
- Consider using semi-synchronous replication to ensure data consistency.
By following these steps, you can successfully set up replication in MySQL. This is crucial for data backup, load balancing, and high availability.