1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

docker-composeでMySQLレプリケーション構築

Last updated at Posted at 2021-04-09

ディレクトリ構成

.
├── docker/
│   ├── primary/
│   │   ├── Dockerfile
│   │   ├── init.sh*
│   │   ├── mysql.cnf
│   │   └── mysqld.cnf
│   └── replica/
│       ├── Dockerfile
│       ├── dockerize-linux-amd64-v0.6.1.tar.gz
│       ├── init.sh*
│       ├── mysql.cnf
│       └── mysqld.cnf
└── docker-compose.yml

Primary

mysqld.cnf
[mysqld]
:
log-bin=ON
server-id=1
gtid-mode=ON
enforce-gtid-consistency=ON
log-slave-updates=ON
init.sh
#!/bin/bash
set -xeo pipefail

mysql -uroot -v <<SQL
CREATE USER 'repl'@'172.16.0.0/255.240.0.0' IDENTIFIED BY 'replpass';
GRANT REPLICATION SLAVE ON *.* TO 'repl'@'172.16.0.0/255.240.0.0';
SQL
Dockerfile
FROM mysql
COPY mysql.cnf /etc/mysql/conf.d/mysql.cnf
COPY mysqld.cnf /etc/mysql/conf.d/mysqld.cnf
COPY init.sh /docker-entrypoint-initdb.d/init.sh

Secondary

mysqld.cnf
[mysqld]
:
log-bin=ON
server-id=2
gtid-mode=ON
enforce-gtid-consistency=ON
log-slave-updates=ON
read-only=ON
init.sh
#!/bin/bash
set -xeo pipefail

dockerize -timeout 60s -wait tcp://primary:3306
sleep 3

mysql -uroot -v <<SQL
CHANGE MASTER TO MASTER_HOST='primary', MASTER_USER='repl', MASTER_PASSWORD='replpass', MASTER_AUTO_POSITION=1;
START SLAVE;
SQL
Dockerfile
FROM mysql
COPY mysql.cnf /etc/mysql/conf.d/mysql.cnf
COPY mysqld.cnf /etc/mysql/conf.d/mysqld.cnf
COPY init.sh /docker-entrypoint-initdb.d/init.sh

# dockerize
COPY dockerize-linux-amd64-v0.6.1.tar.gz /tmp/
RUN tar -xzf /tmp/dockerize-linux-amd64-v0.6.1.tar.gz -C /usr/local/bin

Docker Compose

docker-compose.yml
version: '3'
services:
  primary:
    build:
      context: ./docker/primary
    environment:
      MYSQL_ALLOW_EMPTY_PASSWORD: 1
    ports:
      - 33061:3306
    volumes:
      - type: volume
        source: primary
        target: /var/lib/mysql
  replica:
    build:
      context: ./docker/replica
    depends_on:
      - primary
    environment:
      MYSQL_ALLOW_EMPTY_PASSWORD: 1
    ports:
      - 33062:3306
    volumes:
      - type: volume
        source: replica
        target: /var/lib/mysql
volumes:
  primary:
  replica:
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?