본문 바로가기

리눅스

[리눅스] MySQL 5.7에서 마스터-슬레이브(Master-Slave) 구성을 설정하는 방법

728x90

MySQL 5.7에서 마스터-슬레이브(Master-Slave) 구성을 설정하는 방법

MySQL 복제 작동 방식

원본URL-https://www.researchgate.net/profile/Peter-Kieseberg/publication/266750134/figure/fig4/AS:919665962393600@1596276860039/How-MySQL-replication-works.png

테스트 환경

호스트 이름 아이피 역할 운영체제 버전 MySQL 버전 Server_id
비고
node1 192.168.56.101 master Ubuntu 22.04.2 LTS Ver 5.7.41 1  
node2 192.168.56.102 slave Ubuntu 22.04.2 LTS Ver 5.7.41 2  
node3 192.168.56.103 slave Ubuntu 22.04.2 LTS Ver 5.7.41 3  

MySQL 5.7에서 마스터-슬레이브(Master-Slave) 구성을 설정하는 방법은 다음과 같습니다.

1. 마스터 서버 설정

마스터 서버의 my.cnf 파일을 열어서 다음 구성을 추가합니다.

[mysqld]
server-id=1
log-bin=mysql-bin
binlog-format=ROW

마스터 서버를 다시 시작(재기동)하여 설정 변경 사항을 적용합니다.

 

MySQL 쉘에 접근

/usr/local/mysql/bin/mysql -uroot -p'mysqlpassword'

Replication User 생성하기

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

마스터 상태 확인

flush tables with read lock;
mysql> flush tables with read lock;
Query OK, 0 rows affected (0.00 sec)
show master status\G
mysql> show master status\G
*************************** 1. row ***************************
             File: mysql-bin.000005
         Position: 771
     Binlog_Do_DB: 
 Binlog_Ignore_DB: 
Executed_Gtid_Set: 
1 row in set (0.00 sec)

 

2. 슬레이브 서버 설정

슬레이브 서버의 my.cnf 파일을 열어서 다음 구성을 추가합니다.

[mysqld]
...
server-id=2
skip-slave-start

슬레이브 서버를 다시 시작하여 설정 변경 사항을 적용합니다.

 

3. 마스터 서버에서 백업 데이터 준비

마스터 서버에서 데이터베이스를 백업하고 이를 슬레이브 서버로 전송하는 방법은 여러 가지가 있습니다.

여기서는 mysqldump를 사용하여 백업하고 백업 파일을 슬레이브 서버로 복사하는 방법을 설명하겠습니다.

mysqldump -u <username> -p <database_name> > backup.sql
/usr/local/mysql/bin/mysqldump -uroot -p'mysqlpassword' --all-databases > allDBbackup-${HOSTNAME}_$(date +%Y%m%d).sql
$ /usr/local/mysql/bin/mysqldump -uroot -p'mysqlpassword' --all-databases > allDBbackup-${HOSTNAME}_$(date +%Y%m%d).sql
mysqldump: [Warning] Using a password on the command line interface can be insecure.

위 명령을 실행하면 backup.sql 파일에 데이터베이스 백업이 저장됩니다.

$ ls -l allDBbackup-node1_20230523.sql
-rw-r--r-- 1 root root 887256 May 23 08:27 allDBbackup-node1_20230523.sql

 

SSH KEY 생성 및 배포

더보기
ssh-keygen -t rsa
ssh-copy-id [email protected]

 

데이터베이스 백업 파일 전송(마스터 서버에서 슬레이브 서버로 전송)

scp allDBbackup-node1_20230523.sql [email protected]:~

 

4. 슬레이브 서버에서 마스터 정보 설정

데이터베이스 임포트

/usr/local/mysql/bin/mysql -uroot -p'mysqlpassword' --force < allDBbackup-node1_20230523.sql

 

MySQL 쉘 접속

/usr/local/mysql/bin/mysql -uroot -p'mysqlpassword'

 

슬레이브 서버로 이동하여 다음 명령을 실행합니다.

CHANGE MASTER TO MASTER_HOST='<마스터_IP>', MASTER_USER='<마스터_사용자>', MASTER_PASSWORD='<마스터_비밀번호>', MASTER_LOG_FILE='<마스터의_binlog_파일>', MASTER_LOG_POS=<마스터의_binlog_위치>;

위 명령에서 다음 정보를 마스터 서버의 설정에 맞게 변경합니다.

  • <마스터_IP>: 마스터 서버의 IP 주소
  • <마스터_사용자>: 마스터 서버의 사용자 이름
  • <마스터_비밀번호>: 마스터 서버의 비밀번호
  • <마스터의_binlog_파일>: 마스터 서버의 현재 이진 로그 파일
  • <마스터의_binlog_위치>: 마스터 서버의 현재 이진 로그 파일의 위치
CHANGE MASTER TO
MASTER_HOST='192.168.56.101',
MASTER_USER='replication_user',
MASTER_PASSWORD='password',
MASTER_LOG_FILE='mysql-bin.000003',
MASTER_LOG_POS=514;
mysql> CHANGE MASTER TO
    -> MASTER_HOST='192.168.56.101',
    -> MASTER_USER='replication_user',
    -> MASTER_PASSWORD='password',
    -> MASTER_LOG_FILE='mysql-bin.000003',
    -> MASTER_LOG_POS=514;
Query OK, 0 rows affected, 2 warnings (0.08 sec)
728x90

 

5. 슬레이브 서버 시작

슬레이브 서버에서 다음 명령을 실행하여 슬레이브 서버를 시작합니다.

START SLAVE;
mysql> start slave;
Query OK, 0 rows affected (0.00 sec)

이 명령을 실행하면 슬레이브 서버가 마스터 서버와의 복제를 시작합니다.

 

6. 마스터 및 슬레이브 상태 확인

슬레이브 서버에서 다음 명령을 실행하여 마스터 및 슬레이브 상태를 확인합니다.

  • 마스터
SHOW MASTER STATUS;
mysql> SHOW MASTER STATUS;
+------------------+----------+--------------+------------------+-------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql-bin.000003 |      514 |              |                  |                   |
+------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)
  • 마스터
SHOW SLAVE HOSTS;
mysql> SHOW SLAVE HOSTS;
+-----------+------+------+-----------+--------------------------------------+
| Server_id | Host | Port | Master_id | Slave_UUID                           |
+-----------+------+------+-----------+--------------------------------------+
|         2 |      | 3306 |         1 | 168e9cb8-f8f7-11ed-993f-080027182df0 |
|         3 |      | 3306 |         1 | 3ebc580f-f8f7-11ed-adcf-080027704bff |
+-----------+------+------+-----------+--------------------------------------+
2 rows in set (0.00 sec)
  • 마스터
show processlist\G
mysql> show processlist\G
*************************** 1. row ***************************
     Id: 5
   User: root
   Host: localhost
     db: NULL
Command: Query
   Time: 0
  State: starting
   Info: show processlist
*************************** 2. row ***************************
     Id: 9
   User: replication_user
   Host: node2:50060
     db: NULL
Command: Binlog Dump
   Time: 125
  State: Master has sent all binlog to slave; waiting for more updates
   Info: NULL
*************************** 3. row ***************************
     Id: 10
   User: replication_user
   Host: node3:38394
     db: NULL
Command: Binlog Dump
   Time: 43
  State: Master has sent all binlog to slave; waiting for more updates
   Info: NULL
3 rows in set (0.00 sec)
  • 슬레이브
show slave status\G
  • node2
mysql> show slave status\G
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.56.101
                  Master_User: replication_user
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000003
          Read_Master_Log_Pos: 514
               Relay_Log_File: node2-relay-bin.000004
                Relay_Log_Pos: 320
        Relay_Master_Log_File: mysql-bin.000003
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB: 
          Replicate_Ignore_DB: 
           Replicate_Do_Table: 
       Replicate_Ignore_Table: 
      Replicate_Wild_Do_Table: 
  Replicate_Wild_Ignore_Table: 
                   Last_Errno: 0
                   Last_Error: 
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 514
              Relay_Log_Space: 527
              Until_Condition: None
               Until_Log_File: 
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File: 
           Master_SSL_CA_Path: 
              Master_SSL_Cert: 
            Master_SSL_Cipher: 
               Master_SSL_Key: 
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error: 
               Last_SQL_Errno: 0
               Last_SQL_Error: 
  Replicate_Ignore_Server_Ids: 
             Master_Server_Id: 1
                  Master_UUID: 3ef5caf4-f619-11ed-96e6-080027704bff
             Master_Info_File: /usr/local/mysql-5.7.41/data/master.info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
           Master_Retry_Count: 86400
                  Master_Bind: 
      Last_IO_Error_Timestamp: 
     Last_SQL_Error_Timestamp: 
               Master_SSL_Crl: 
           Master_SSL_Crlpath: 
           Retrieved_Gtid_Set: 
            Executed_Gtid_Set: 
                Auto_Position: 0
         Replicate_Rewrite_DB: 
                 Channel_Name: 
           Master_TLS_Version: 
1 row in set (0.00 sec)
  • node3
mysql> show slave status\G
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.56.101
                  Master_User: replication_user
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000003
          Read_Master_Log_Pos: 514
               Relay_Log_File: node3-relay-bin.000006
                Relay_Log_Pos: 320
        Relay_Master_Log_File: mysql-bin.000003
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB: 
          Replicate_Ignore_DB: 
           Replicate_Do_Table: 
       Replicate_Ignore_Table: 
      Replicate_Wild_Do_Table: 
  Replicate_Wild_Ignore_Table: 
                   Last_Errno: 0
                   Last_Error: 
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 514
              Relay_Log_Space: 527
              Until_Condition: None
               Until_Log_File: 
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File: 
           Master_SSL_CA_Path: 
              Master_SSL_Cert: 
            Master_SSL_Cipher: 
               Master_SSL_Key: 
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error: 
               Last_SQL_Errno: 0
               Last_SQL_Error: 
  Replicate_Ignore_Server_Ids: 
             Master_Server_Id: 1
                  Master_UUID: 3ef5caf4-f619-11ed-96e6-080027704bff
             Master_Info_File: /usr/local/mysql-5.7.41/data/master.info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
           Master_Retry_Count: 86400
                  Master_Bind: 
      Last_IO_Error_Timestamp: 
     Last_SQL_Error_Timestamp: 
               Master_SSL_Crl: 
           Master_SSL_Crlpath: 
           Retrieved_Gtid_Set: 
            Executed_Gtid_Set: 
                Auto_Position: 0
         Replicate_Rewrite_DB: 
                 Channel_Name: 
           Master_TLS_Version: 
1 row in set (0.00 sec)

이러한 명령을 실행하면 마스터 및 슬레이브 서버의 상태 정보가 표시됩니다. 슬레이브 서버의 Slave_IO_Running 및 Slave_SQL_Running 값이 Yes로 표시되는지 확인하여 복제가 제대로 작동하는지 확인할 수 있습니다.

 

이제 MySQL 5.7에서 마스터-슬레이브 구성을 설정했습니다. 마스터 서버에서 데이터베이스 변경이 발생하면 해당 변경이 슬레이브 서버로 자동으로 복제될 것입니다.

 

728x90