基于docker搭建mysql主从环境
博主本机环境为:虚拟机ubuntu 18.04,mysql 5.7镜像
1. 拉取mysql 5.7的docker镜像
docker pull daocloud.io/library/mysql:5.7
2. 准备主从配置
主库配置:/opt/mysql/my-data/master/mysql-3308.cnf
[mysqld] pid-file = /var/run/mysqld/mysqld.pid socket = /var/run/mysqld/mysqld.sock datadir = /var/lib/mysql symbolic-links=0 character-set-server=utf8 default-storage-engine=INNODB sql_mode=STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION server-id=1 log_bin=/var/log/mysql/binlog
从库配置:/opt/mysql/my-data/slave/mysql-3309.cnf
[mysqld] pid-file = /var/run/mysqld/mysqld.pid socket = /var/run/mysqld/mysqld.sock datadir = /var/lib/mysql symbolic-links=0 character-set-server=utf8 default-storage-engine=INNODB sql_mode=STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION server-id=2 log_bin=/var/log/mysql/binlog innodb_file_per_table=ON skip_name_resolve=ON binlog-format=row log-slave-updates=true relay_log=/var/log/mysql/relay.log
3. 创建容器,使用我们指定的配置,主库对外使用3308端口,从库使用3309端口
docker run --name mysqldb1 -v /opt/mysql/my-data/master/mysql-3308.cnf:/etc/mysql/my.cnf -p 3308:3306 -e MYSQL_ROOT_PASSWORD=123456 -d daocloud.io/library/mysql:5.7
docker run --name mysqldb2 -v /opt/mysql/my-data/slave/mysql-3309.cnf:/etc/mysql/my.cnf -p 3309:3306 -e MYSQL_ROOT_PASSWORD=123456 -d daocloud.io/library/mysql:5.7
4. 此时可以使用工具连接到主库和从库,查看其server_id,是否是我们配置的server_id
5. 连接主库,查看主库状态,记下这里的File和Position
show master status;
6. 虚拟机开放3308端口
iptables -I INPUT -p tcp --dport 3308 -j ACCEPT
7. 连接从库,执行命令。这里的MASTER_LOG_FILE和MASTER_LOG_POS分别对应步骤5中查到的File和Position
stop slave ; CHANGE MASTER TO MASTER_HOST='192.168.92.130',MASTER_PORT =3308,MASTER_USER='root', MASTER_PASSWORD='123456',MASTER_LOG_FILE='binlog.000003',MASTER_LOG_POS=154; start slave ;
8. 查看从库状态,如下图所示,则表示正常
9. 可以进行测试,在主库创建数据库和建表,都会同步到从库