How to implement MySQL master-slave replication in Ubuntu

1. Install MySQL

MySQL server can be installed on Ubuntu using the apt-get tool. Enter the following command in the terminal:

sudo apt-get update
sudo apt-get install mysql-server

 Enter service mysql status to ensure that mysql is running normally:

2. Configure the main server

Edit the /etc/mysql/mysql.conf.d/mysqld.cnf file and add the following configuration at the end of the file:

server-id=1
log_bin=/var/log/mysql/mysql-bin.log
binlog_do_db=mydatabase

Among them, server-id represents the unique identifier of the MySQL instance, log_bin specifies the location and file name of the binary log file, and binlog_do_db specifies the name of the database that needs to be copied.

3. Restart the MySQL server

Enter the following command in the terminal:

sudo service mysql restart

4. Create a replication account on the master server

Execute the following SQL command in MySQL:

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

Among them, slave_ip represents the IP address of the slave server, and password is the password of the replication account.

5. Obtain the binary log information of the main server

Execute the following SQL command in MySQL:

SHOW MASTER STATUS;

Record the values ​​of File and Position, which will be used by the slave server later.

6. Configure slave server

Edit the /etc/mysql/mysql.conf.d/mysqld.cnf file and add the following configuration at the end of the file:

server-id=2
replicate-do-db=mydatabase

Among them, server-id represents the unique identifier of the MySQL instance, and replicate-do-db specifies the name of the database that needs to be replicated.

7. Restart the MySQL server

Enter the following command in the terminal:

sudo service mysql restart

8. Start the replication process from the slave server:

Execute the following SQL command in MySQL:

CHANGE MASTER TO MASTER_HOST='master_ip', MASTER_USER='replication', MASTER_PASSWORD='password', MASTER_LOG_FILE='mysql-bin.000002', MASTER_LOG_POS=157;

START SLAVE;

Among them, master_ip is the IP address of the master server, password is the password of the replication account, MASTER_LOG_FILE and MASTER_LOG_POS are the name and location of the binary log file on the master server respectively, which need to be modified according to the information in step 5.

At this point, the MySQL master-slave replication configuration on Ubuntu is complete!

Guess you like

Origin blog.csdn.net/weixin_51418964/article/details/130280008