MySQL/MySQLレプリケーション

MySQLレプリケーション

dokuwiki.fl8.jp転載済

レプリケーションとは、あるデータベースから他のデータベースに複製を作ることです。

構成

MySQL 5.1.30

[マスター側]

レプリケーション用ユーザを作成

mysql> GRANT REPLICATION SLAVE ON *.* TO repl@'%' IDENTIFIED BY '<password>';

マスタサーバで更新ログを有効にする

マスタサーバで更新ログ(バイナリログとも言う)を有効にします。
my.cnf ファイルに以下の記述があるか確認して下さい。

[mysqld]
log-bin
server-id=1

※server-id は、1以上の整数であれば何でも良いです。

テーブルへの書き込みを禁止

mysql> FLUSH TABLES WITH READ LOCK;

マスタデータのスナップショットを撮る(tarで固める)

# cd /home/mysql
# tar zcvf data.tar.gz data
# scp data.tar.gz [スレーブサーバ]

更新ログの状態を取得する

実行したら、画面に出力された「File」と「Position」カラムの内容をメモしておきます。
これは、現時点での更新ログファイル名とそのオフセットです。
この後スレーブサーバ上でレプリケーションを有効にする際に必要になります。

mysql> SHOW MASTER STATUS;

ロックを解除

mysql> UNLOCK TABLES;

バイナリログの自動削除

確認コマンド

mysql> show global variables like 'expire_logs_days';

デフォルトの0は削除しないの意味

my.cnfに下記を書いておけば、14日で削除される。

set-variable = expire_logs_days=14

[スレーブ側]

スナップショットを展開する

# cd /home/mysql
# tar zxvf data.tar.gz

my.cnf設定

server-id       = 2
master-host     = 172.16.8.53
master-port     = 3306
master-user     = slave
master-password = xxslave

レプリケーションを行う準備

mysql> STOP SLAVE;
mysql> CHANGE MASTER TO
          MASTER_HOST='<master host name>',
          MASTER_USER='<replication user name>',
          MASTER_PASSWORD='<replication password>',
          MASTER_LOG_FILE='<recorded log file name>',
          MASTER_LOG_POS=<recorded log offset>;

mysql> START SLAVE;

スレーブの状態確認

mysql> show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 172.16.8.53
                  Master_User: slave
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000007
          Read_Master_Log_Pos: 19072
               Relay_Log_File: localhost-relay-bin.000002
                Relay_Log_Pos: 8504
        Relay_Master_Log_File: mysql-bin.000007
             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: 19072
              Relay_Log_Space: 8663
              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: 
1 row in set (0.00 sec)

ERROR: 
No query specified