Hugh's Blog

Docker + MySQL 主从环境

 

只是简单的搭建环境进行测试,做个记录。

MySQL 配置

建立相应的 cnf 配置文件,注意 server_id 需要保证唯一。

master/my.cnf

[mysqld]
server_id=1
log-bin=mysql-bin
read-only=0
## 指定同步数据库
# binlog-do-db=example
## 忽略同步数据库
# replicate-ignore-db=mysql
# replicate-ignore-db=sys
# replicate-ignore-db=information_schema
# replicate-ignore-db=performance_schema

!includedir /etc/mysql/conf.d/
!includedir /etc/mysql/mysql.conf.d/

slave/my.cnf

[mysqld]
server_id=2
log-bin=mysql-bin
read-only=1
## 指定同步数据库
# binlog-do-db=example
## 忽略同步数据库
# replicate-ignore-db=mysql
# replicate-ignore-db=sys
# replicate-ignore-db=information_schema
# replicate-ignore-db=performance_schema

!includedir /etc/mysql/conf.d/
!includedir /etc/mysql/mysql.conf.d/

Docker 配置

docker-compose.yml

version: '2'
services:
  mysql-master:
    image: mysql:latest
    container_name: mysql_master
    volumes:
      - ./master/my.cnf:/etc/mysql/my.cnf
    environment:
      - MYSQL_ROOT_PASSWORD=123456
    command: ['mysqld', '--character-set-server=utf8']

  mysql-slave:
    image: mysql:latest
    container_name: mysql_slave
    volumes:
      - ./slave/my.cnf:/etc/mysql/my.cnf
    environment:
      - MYSQL_ROOT_PASSWORD=123456
    links:
      - "mysql-master:master"
    command: ['mysqld', '--character-set-server=utf8']

  phpmyadmin_1:
    image: phpmyadmin/phpmyadmin
    container_name: mysql_admin_1
    links:
      - "mysql-master:db"
    ports:
      - "8080:80"

  phpmyadmin_2:
    image: phpmyadmin/phpmyadmin
    container_name: mysql_admin_2
    links:
      - "mysql-slave:db"
    ports:
      - "8081:80"

启动容器

docker-compose up -d

# 进入到 slave 容器
docker exec -it mysql_slave bash

# 在 slave 容器中登录 master mysql
mysql -u root -p -h master

# 建立同步用户 backup 并记录下 File 与 Position 的值,后面 slave 会用到
# *************************** 1. row ***************************
#             File: mysql-bin.000003
#         Position: 431
#     Binlog_Do_DB:
# Binlog_Ignore_DB:
mysql> GRANT REPLICATION SLAVE ON *.* to 'backup'@'%' identified by '123456';
mysql> show master status\G;

# 退出并登录到当前 salve mysql
mysql -u root -p

# 连接 master,并启动 slave
# 如果看到 Slave_IO_Running: Yes 与 Slave_SQL_Running: Yes 说明连接成功
mysql> change master to master_host='master',master_user='backup',master_password='123456',master_log_file='mysql-bin.000003',master_log_pos=431,master_port=3306;
mysql> start slave;
mysql> show slave status\G;

连接成功之后可以使用 phpmyadmin 进行简单的测试。