docker如何搭建mysql主从?

妙蛙种子

1 Docker 搭建 mysql 主从

下载 docker 镜像

docker pull mysql

2 创建网络驱动

docker network create {网络名称} 创建专门用于容器之间通信的网络

作用: 创建 docker 容器的时候 通过 --network {网络名称} 可以方便在内部使用容器名称进行通信

docker network create cusnet

3 主服务器搭建

3.1 启动主服务器

docker run -dit  --network cusnet --name mysql_master -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 mysql

3.2 修改主服务器的配置

  • 进入容器中docker exec -it mysql_master /bin/bash
  • 修改配置文件cd /etc/mysql
    echo "[mysqld]" > my.cnf
    echo "pid-file = /var/run/mysqld/mysqld.pid" >> my.cnf
    echo "socket = /var/run/mysqld/mysqld.sock" >> my.cnf
    echo "datadir = /var/lib/mysql" >> my.cnf
    echo "secure-file-priv= NULL" >> my.cnf
    echo "secure-file-priv= NULL" >> my.cnf
    echo "log-bin=/var/run/mysqld/mysql-bin" >> my.cnf # [必须]启用二进制日志echo "server-id=1" >> my.cnf # [必须]服务器唯一ID
    set +H
    echo "!includedir /etc/mysql/conf.d/" >> my.cnf
  • 创建用于复制的账号$ mysql -uroot -p123456
    mysql> CREATE USER 'slave'@'%' IDENTIFIED BY '123456';mysql> GRANT REPLICATION SLAVE, REPLICATION CLIENT ON . TO 'slave'@'%';
  • 关闭容器重启 docker container stop mysql_master && docker container start mysql_master

4 从服务器搭建

4.1 启动从服务器

docker run -dit  --network cusnet --name mysql_slave -p 3307:3306 -e MYSQL_ROOT_PASSWORD=123456 mysql

4.2 修改从服务器的配置

  • 进入容器中docker exec -it mysql_slave /bin/bash
  • 修改配置文件cd /etc/mysql
    echo "[mysqld]" > my.cnf
    echo "pid-file = /var/run/mysqld/mysqld.pid" >> my.cnf
    echo "socket = /var/run/mysqld/mysqld.sock" >> my.cnf
    echo "datadir = /var/lib/mysql" >> my.cnf
    echo "secure-file-priv= NULL" >> my.cnf
    echo "secure-file-priv= NULL" >> my.cnf
    echo "log-bin=/var/run/mysqld/mysql-bin" >> my.cnf # [必须]启用二进制日志echo "relay_log=/var/run/mysqld/mysql-relay-bin" >> my.cnf
    echo "server-id=2" >> my.cnf # [必须]服务器唯一ID
    set +H
    echo "!includedir /etc/mysql/conf.d/" >> my.cnf
  • 关闭容器重启 docker container stop mysql_slave && docker container start mysql_slave
  • 连接到 master$ mysql -uroot -p123456
    ​mysql> show master status G; ;; 这句话是查看 master 日志文件和当前的位置mysql> CHANGE MASTER TO GET_MASTER_PUBLIC_KEY=1;mysql> change master to MASTER_HOST='mysql_master',MASTER_USER='slave',MASTER_PASSWORD='123456',MASTER_LOG_FILE="mysql-bin.000001",MASTER_LOG_POS=156;mysql> start slave; ;; 启动复制mysql> show slave status G; ;; 查看复制的状态如果报 (1872, 'Slave failed to initialize relay log info structure from the repository')执行 reset slave;
阅读 1.6k
4 声望
1 粉丝
0 条评论
4 声望
1 粉丝
文章目录
宣传栏