How to set up MySQL master-slave replication?
To set up MySQL master-slave replication, you need to follow these steps:
- Set up the primary database (Master):
- Open the configuration file of the main database (usually my.cnf or my.ini), and enable the binary log feature. Add the following lines to the file:
log-bin = mysql-bin
server-id = 1 - Reboot the main database to apply the settings.
- Configuration from the database (Slave):
- Open the configuration file from the database and enable the server functionality. Add the following line in the file: server-id = 2.
- Restart the database for the configuration to take effect.
- Create a user for replication on the primary database.
- Log in to the main database and execute the following SQL statements to create a replication user: CREATE USER ‘replication_user’@’%’ IDENTIFIED BY ‘password’;
GRANT REPLICATION SLAVE ON *.* TO ‘replication_user’@’%’;
FLUSH PRIVILEGES; - Back up the primary database and restore the backup to the secondary database.
- Execute the following command on the main database to create a database backup file: mysqldump -u username -p dbname > backup.sql
- Transfer the backup file to the database, and restore the backup using the following command: mysql -u username -p dbname < backup.sql
- Setting up a master-slave relationship from the database:
- Login to the database and execute the following SQL statement: CHANGE MASTER TO MASTER_HOST=’master_ip’, MASTER_USER=’replication_user’, MASTER_PASSWORD=’password’, MASTER_LOG_FILE=’mysql-bin.000001′, MASTER_LOG_POS=123;
Where ‘master_ip’ is the IP address of the master database, ‘mysql-bin.000001’ is the latest binary log file in the master database, and 123 is the replication position in the master database.
- Initiate the replication process from the database.
- Execute the following SQL statement to start the replication process: START SLAVE;
- Check the status of master-slave synchronization.
- Execute the following SQL statement to check the status of master-slave synchronization: SHOW SLAVE STATUS\G
Check if the values of the “Slave_IO_Running” and “Slave_SQL_Running” fields in the output are “YES”, indicating that the master-slave synchronization has been successfully established.
After completing the above steps, your MySQL master-slave synchronization has been successfully set up. Updates on the master database will be automatically replicated to the slave database.