准备两台服务器,假设IP地址为
172.31.27.67 主服务器
172.31.27.69 从服务器
因为我用的镜像是docker.io/cytopia/mysql-8.0,所以我们需要先把该镜像给pull下来。
docker pull docker.io/cytopia/mysql-8.0
在/home下建一个文件夹
mkdir /home/wen
在主服务器建一个master.my.cnf
内容如下
[client]
socket = /var/sock/mysqld/mysqld.sock [mysql] socket = /var/sock/mysqld/mysqld.sock [mysqld] skip-host-cache skip-name-resolve datadir = /var/lib/mysql user = mysql port = 3306 bind-address = 0.0.0.0 socket = /var/sock/mysqld/mysqld.sock pid-file = /var/run/mysqld/mysqld.pid general_log_file = /var/log/mysql/query.log slow_query_log_file = /var/log/mysql/slow.log log-error = /var/log/mysql/error.log log-bin=mysql-bin server-id=1 !includedir /etc/my.cnf.d/ !includedir /etc/mysql/conf.d/ !includedir /etc/mysql/docker-default.d/在从服务器建一个slave.my.cnf,内容如下
[client]
socket = /var/sock/mysqld/mysqld.sock [mysql] socket = /var/sock/mysqld/mysqld.sock [mysqld] skip-host-cache skip-name-resolve datadir = /var/lib/mysql user = mysql port = 3306 bind-address = 0.0.0.0 socket = /var/sock/mysqld/mysqld.sock pid-file = /var/run/mysqld/mysqld.pid general_log_file = /var/log/mysql/query.log slow_query_log_file = /var/log/mysql/slow.log log-error = /var/log/mysql/error.log log-bin=mysql-bin server-id=2 !includedir /etc/my.cnf.d/ !includedir /etc/mysql/conf.d/ !includedir /etc/mysql/docker-default.d/这里他们的server-id要区分开
在主服务器启动(密码由你自己设定)
docker run -d --name mysql -e MYSQL_ROOT_PASSWORD=abcd123 -p 3307:3306 -v /etc/localtime:/etc/localtime:ro -v /home/wen/master.my.cnf:/etc/my.cnf docker.io/cytopia/mysql-8.0
在从服务器启动
docker run -d --name mysql -e MYSQL_ROOT_PASSWORD=abcd123 -p 3306:3306 -v /etc/localtime:/etc/localtime:ro -v /home/wen/slave.my.cnf:/etc/my.cnf docker.io/cytopia/mysql-8.0
使用数据库连接工具进行连接,先连接主服务器的数据库
依次执行
GRANT REPLICATION SLAVE ON *.* TO 'root'@'%';
flush privileges;
show master status;
可以看到主数据库的状态
切换到从数据库,依次执行
CHANGE MASTER TO
MASTER_HOST='172.31.27.67', MASTER_PORT=3307, MASTER_USER='root', MASTER_PASSWORD='abcd123', MASTER_LOG_FILE='mysql-bin.000003', MASTER_LOG_POS=6143;start slave;
show slave status;
如果我们看到
其中Slave_IO_Running,Slave_SQL_Running必须为Yes,表示同步成功,否则执行
stop slave;
将之前的动作重新执行一遍。之后我们在主库做的SQL语句执行,会同步到从库中来。