MySQLのmaster slave構成をDockerで試す

2 min read

研修で触ったときにサクッと動かなかったので追試的に。MySQLは8.0を使う。

repo image

レプリケーション自体の仕組みは 進化を続けるMySQLのド定番機能 MySQLレプリケーション最新機能 がわかりやすかった。

必要なこと

How To Set Up Master Slave Replication in MySQL | DigitalOcean

このページを見ながらmasterとslaveのmysqldを1つずつ用意して、設定を行う。異なる点は下記。

create user 'slave_user'@'%' identified by 'password';
grant replication slave on *.* to 'slave_user'@'%' with grant option;
flush privileges;
  • GTIDを有効にして MASTER_LOG_FILEMASTER_LOG_POS は自動で検知されるようにする。
CHANGE MASTER TO MASTER_HOST='mysql-master',MASTER_USER='slave_user',MASTER_PASSWORD='password',MASTER_AUTO_POSITION=1;
START SLAVE;

レプリケーションを確認する

$ git clone https://github.com/raahii/docker-mysql-master-slave.git
$ cd docker-mysql-master-slave
$ docker-compose up -d
$ docker-compose ps
    Name                 Command             State                 Ports
--------------------------------------------------------------------------------------
mysql-master   docker-entrypoint.sh mysqld   Up      0.0.0.0:3306->3306/tcp, 33060/tcp
mysql-slave    docker-entrypoint.sh mysqld   Up      0.0.0.0:3307->3306/tcp, 33060/tcp

  • masterのステータスを確認
$ docker-compose exec mysql-master sh -c "export MYSQL_PWD=password; mysql -u root app -e 'show master status\G'" 
*************************** 1. row ***************************
             File: mysql-bin.000001
         Position: 156
     Binlog_Do_DB: app
 Binlog_Ignore_DB: 
Executed_Gtid_Set: 
  • slaveのステータスを確認
$ docker-compose exec mysql-slave sh -c "export MYSQL_PWD=password; mysql -u root app -e 'show slave status\G'" 
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: mysql-master
                  Master_User: slave_user
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000001
          Read_Master_Log_Pos: 156
               Relay_Log_File: mysql-relay-bin.000004
                Relay_Log_Pos: 371
        Relay_Master_Log_File: mysql-bin.000001
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
                            :
                            :
  • masterにテーブルを作ってレコードをinsert
$ docker-compose exec mysql-master sh -c “export MYSQL_PWD=password; mysql -u root app -e ‘create table code(code int); insert into code values (100), (200)’”
  • 変更が slave に反映されていることを確認
$ docker-compose exec mysql-slave sh -c "export MYSQL_PWD=password; mysql -u root app -e 'select * from code \G'"
*************************** 1. row ***************************
code: 100
*************************** 2. row ***************************
code: 200

テーブルも作られているし、レコードも入っている。良さそう。

参考

comments powered by Disqus

こちらの記事もどうぞ