首页 > 数据库 >mysql8主从复制(一主三从) docker

mysql8主从复制(一主三从) docker

时间:2023-03-23 16:48:17浏览次数:50  
标签:COMMENT 主从复制 NULL mysql8 DEFAULT master mysql 一主三 id

一、准备挂载文件

为了将配置文件在宿主机做挂载,先运行测试镜像拷贝配置文件

1、拉取镜像

docker pull mysql:8.0.26

2、创建测试容器mysql-demo

docker run -it -p 3300:3306 \
--name mysql-demo \
-e MYSQL_ROOT_PASSWORD=123456 \
-d mysql:8.0.26

运行时改成一排执行:

docker run -it -p 3300:3306 --name mysql-demo -e MYSQL_ROOT_PASSWORD=123456 -d mysql:8.0.26

3、在root目录下创建mysql-master文件夹,在mysql-master文件夹下创建conf和data文件夹。

mkdir mysql-master
mkdir -p ~/mysql-master/conf ~/mysql-master/data

4、将mysql-demo容器内的/etc/mysql/my.cnf文件拷贝到~/mysql-master/conf目录下

docker cp mysql-demo:/etc/mysql/my.cnf ~/mysql-master/conf

5、将mysql-master中的内容全部拷贝到mysql-slave中

cp -r ~/mysql-master ~/mysql-slave1
cp -r ~/mysql-master ~/mysql-slave2
cp -r ~/mysql-master ~/mysql-slave3

6、停止并删除测试容器

docker stop mysql-demo
docker rm mysql-demo

二、创建自定义网络

默认的bridge 网桥无法指定固定的ip,会导致mysql服务的ip不固定,最好配置为自定义网络

docker network create --driver bridge --subnet 192.172.0.0/16 --gateway 192.172.0.1 newnet

查看网络

[root@xxx conf]# docker network ls
NETWORK ID     NAME      DRIVER    SCOPE
dfd016599931   bridge    bridge    local
9951733f6b75   host      host      local
8efcdae3efd4   newnet    bridge    local
9eae2373bc1f   none      null      local

三、创建主从容器

创建两个自定义网路的MySQL容器,使用newnet定义IP时,前面两个数字要与newnet的对应,后面两个可以随便指定,但不能超过255

1、创建主容器

复制代码
docker run -it -p 3301:3306 \
--name mysql-master \
--net newnet --ip 192.172.0.30 \
-v ~/mysql-master/conf/my.cnf:/etc/mysql/my.cnf \
-v ~/mysql-master/data:/var/lib/mysql \
--privileged=true \
--restart=always \
-e MYSQL_ROOT_PASSWORD=123456 \
-e TZ=Asia/Shanghai \
mysql:8.0.26
复制代码

执行时去掉\改成一排

docker run -it -p 3301:3306 --name mysql-master --net newnet --ip 192.172.0.30 -v ~/mysql-master/conf/my.cnf:/etc/mysql/my.cnf -v ~/mysql-master/data:/var/lib/mysql --privileged=true --restart=always -e MYSQL_ROOT_PASSWORD=123456 -e TZ=Asia/Shanghai mysql:8.0.26

控制台打印日志如下:

复制代码
[root@xxx conf]# docker run -it -p 3301:3306 --name mysql-master --net newnet --ip 192.172.0.30 -v ~/mysql-master/conf/my.cnf:/etc/mysql/my.cnf -v ~/mysql-master/data:/var/lib/mysql --privileged=true --restart=always -e MYSQL_ROOT_PASSWORD=123456 -e TZ=Asia/Shanghai mysql:8.0.26
2022-07-23 09:58:48+08:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.26-1debian10 started.
2022-07-23 09:58:48+08:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
2022-07-23 09:58:48+08:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.26-1debian10 started.
2022-07-23 09:58:48+08:00 [Note] [Entrypoint]: Initializing database files
2022-07-23T01:58:48.354370Z 0 [System] [MY-013169] [Server] /usr/sbin/mysqld (mysqld 8.0.26) initializing of server in progress as process 43
2022-07-23T01:58:48.363794Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
2022-07-23T01:58:49.105917Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
2022-07-23T01:58:50.972408Z 0 [Warning] [MY-013746] [Server] A deprecated TLS version TLSv1 is enabled for channel mysql_main
2022-07-23T01:58:50.972752Z 0 [Warning] [MY-013746] [Server] A deprecated TLS version TLSv1.1 is enabled for channel mysql_main
2022-07-23T01:58:51.081275Z 6 [Warning] [MY-010453] [Server] root@localhost is created with an empty password ! Please consider switching off the --initialize-insecure option.
2022-07-23 09:58:55+08:00 [Note] [Entrypoint]: Database files initialized
2022-07-23 09:58:55+08:00 [Note] [Entrypoint]: Starting temporary server
mysqld will log errors to /var/lib/mysql/f0d909d9adcb.err
mysqld is running as pid 94
2022-07-23 09:58:56+08:00 [Note] [Entrypoint]: Temporary server started.
Warning: Unable to load '/usr/share/zoneinfo/iso3166.tab' as time zone. Skipping it.
Warning: Unable to load '/usr/share/zoneinfo/leap-seconds.list' as time zone. Skipping it.
Warning: Unable to load '/usr/share/zoneinfo/zone.tab' as time zone. Skipping it.
Warning: Unable to load '/usr/share/zoneinfo/zone1970.tab' as time zone. Skipping it.

2022-07-23 09:58:58+08:00 [Note] [Entrypoint]: Stopping temporary server
2022-07-23 09:59:01+08:00 [Note] [Entrypoint]: Temporary server stopped

2022-07-23 09:59:01+08:00 [Note] [Entrypoint]: MySQL init process done. Ready for start up.

2022-07-23T01:59:01.295583Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.26) starting as process 1
2022-07-23T01:59:01.306472Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
2022-07-23T01:59:01.508782Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
2022-07-23T01:59:01.729201Z 0 [Warning] [MY-013746] [Server] A deprecated TLS version TLSv1 is enabled for channel mysql_main
2022-07-23T01:59:01.729347Z 0 [Warning] [MY-013746] [Server] A deprecated TLS version TLSv1.1 is enabled for channel mysql_main
2022-07-23T01:59:01.730375Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
2022-07-23T01:59:01.730543Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel.
2022-07-23T01:59:01.734139Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
2022-07-23T01:59:01.753416Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Bind-address: '::' port: 33060, socket: /var/run/mysqld/mysqlx.sock
2022-07-23T01:59:01.753477Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.26'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server - GPL.
复制代码

2、创建三个从容器

复制代码
docker run -it -p 3302:3306 \
--name mysql-slave1 \
--net newnet --ip 192.172.0.31 \
-v ~/mysql-slave1/conf/my.cnf:/etc/mysql/my.cnf \
-v ~/mysql-slave1/data:/var/lib/mysql \
--privileged=true \
--restart=always \
-e MYSQL_ROOT_PASSWORD=123456 \
-e TZ=Asia/Shanghai \
mysql:8.0.26
复制代码

执行时去掉\改为一行执行

docker run -it -p 3302:3306 --name mysql-slave1 --net newnet --ip 192.172.0.31 -v ~/mysql-slave1/conf/my.cnf:/etc/mysql/my.cnf -v ~/mysql-slave1/data:/var/lib/mysql --privileged=true --restart=always -e MYSQL_ROOT_PASSWORD=123456 -e TZ=Asia/Shanghai mysql:8.0.26
docker run -it -p 3303:3306 --name mysql-slave2 --net newnet --ip 192.172.0.32 -v ~/mysql-slave2/conf/my.cnf:/etc/mysql/my.cnf -v ~/mysql-slave2/data:/var/lib/mysql --privileged=true --restart=always -e MYSQL_ROOT_PASSWORD=123456 -e TZ=Asia/Shanghai mysql:8.0.26
docker run -it -p 3304:3306 --name mysql-slave3 --net newnet --ip 192.172.0.33 -v ~/mysql-slave3/conf/my.cnf:/etc/mysql/my.cnf -v ~/mysql-slave3/data:/var/lib/mysql --privileged=true --restart=always -e MYSQL_ROOT_PASSWORD=123456 -e TZ=Asia/Shanghai mysql:8.0.26

此时已经启动了四个容器mysql-master和mysql-slave1、mysql-slave2、mysql-slave3

CONTAINER ID   IMAGE          COMMAND                  CREATED              STATUS              PORTS                                                  NAMES
ce70f22a2cfc   mysql:8.0.26   "docker-entrypoint.s…"   44 seconds ago       Up 43 seconds       33060/tcp, 0.0.0.0:3304->3306/tcp, :::3304->3306/tcp   mysql-slave3
bc042e5c2316   mysql:8.0.26   "docker-entrypoint.s…"   About a minute ago   Up About a minute   33060/tcp, 0.0.0.0:3303->3306/tcp, :::3303->3306/tcp   mysql-slave2
dda81d5cae65   mysql:8.0.26   "docker-entrypoint.s…"   3 minutes ago        Up 3 minutes        33060/tcp, 0.0.0.0:3302->3306/tcp, :::3302->3306/tcp   mysql-slave1
f3d96b38f6bb   mysql:8.0.26   "docker-entrypoint.s…"   5 minutes ago        Up 5 minutes        33060/tcp, 0.0.0.0:3301->3306/tcp, :::3301->3306/tcp   mysql-master

查看newnet网络

命令:

docker network inspect newnet

部分结果如下:

"Containers": {
            "bc042e5c23161e48cc54bdf6d818b20b97062035358f1a7e698628b81ef610f3": {
                "Name": "mysql-slave2",
                "EndpointID": "983bb94b217cf73b2e9b8a0fcffc20d6c3d37bc8699dcd8848be845cb80be42d",
                "MacAddress": "02:42:c0:ac:00:20",
                "IPv4Address": "192.172.0.32/16",
                "IPv6Address": ""
            },
            "ce70f22a2cfc1e85cf3a23c7979e75cdbe538a76867d14a65378056460f1d3ce": {
                "Name": "mysql-slave3",
                "EndpointID": "78d0f1d87c2c231178eceace404b15051ca5601724fc5f0b2c0e6f493003d7d1",
                "MacAddress": "02:42:c0:ac:00:21",
                "IPv4Address": "192.172.0.33/16",
                "IPv6Address": ""
            },
            "dda81d5cae653bbf6611f27be7a3f44c9c3214750233b77b31d7a3aa75cd9b01": {
                "Name": "mysql-slave1",
                "EndpointID": "0db304928fc343e81e17c6e9371392d3d080f980d185765cc06580325b1e9244",
                "MacAddress": "02:42:c0:ac:00:1f",
                "IPv4Address": "192.172.0.31/16",
                "IPv6Address": ""
            },
            "f3d96b38f6bb47c7a7b70c7472a97010e7262fa4f422d59ef5dedbcfaf8b4679": {
                "Name": "mysql-master",
                "EndpointID": "04848f2d83932d0d07634a921bef961f2fef4b1e768a2fc730917bfd75001d22",
                "MacAddress": "02:42:c0:ac:00:1e",
                "IPv4Address": "192.172.0.30/16",
                "IPv6Address": ""
            }
        },

如果是云服务器,则要在安全组放开3301、3302、3303、3304端口。

本地电脑的navicat访问mysql-master

 发现该数据库中已经有了msyql自带的四个数据库。

3、修改主容器的my.conf文件

在宿主机中,配置mysql-master挂载的my.cnf文件

编辑my.cnf文件

vim ~/mysql-master/conf/my.cnf

在my.cnf文件中放入如下内容

复制代码
server-id=100
log-bin=master-bin #开启二进制文件
#binlog-do-db=demo    #需要同步的二进制数据库名;
binlog-ignore-db=information_schema    #不同步的二进制数据库名,如果不设置可以将其注释掉;
binlog-ignore-db=mysql
binlog-ignore-db=performance_schema
binlog-ignore-db=sys
#log-slave-update  #这个是把更新的记录写到二进制文件中;
复制代码

如下所示:

复制代码
# Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA

#
# The MySQL  Server configuration file.
#
# For explanations see
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html

[mysqld]
pid-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock
datadir         = /var/lib/mysql
secure-file-priv= NULL

# Custom config should go here
!includedir /etc/mysql/conf.d/
server-id=100
log-bin=master-bin
#binlog-do-db=demo   
binlog-ignore-db=information_schema 
binlog-ignore-db=mysql
binlog-ignore-db=performance_schema
binlog-ignore-db=sys
#log-slave-update
复制代码

 server-id: 唯一服务器ID不能和其他服务器的server-id重复;

log-bin文件的命名方式: 名称为hostname-bin.xxxxx (重启mysql一次将会自动生成一个新的binlog)

4、重启mysql-master使配置生效

配置完成后,需要重启mysql-master容器使其修改的配置文件生效,使用如下命令使mysql进行重启

docker restart mysql-master

四、配置mysql-slave1、mysql-slave2、mysql-slave3的my.cnf文件

相同方法配置mysql-slave挂载的my.cnf文件

1、编辑my.cnf文件

vim ~/mysql-slave1/conf/my.cnf

2、添加如下配置

复制代码
# 设置server_id,注意要唯一
server-id=101  
# 开启二进制日志功能,以备Slave作为其它Slave的Master时使用
log-bin=slave1-bin   
# relay_log配置中继日志
relay_log=/var/lib/mysql/relay.log  
read_only=1  # 设置为只读,该项如果不设置,表示slave可读可写
复制代码

relay_log的作用:

master主节点的binlog传到slave从节点后,被写到relay log里,从节点的slave sql线程从relaylog里读取日志然后应用到slave从节点本地。即从服务器I/O线程将主服务器的二进制日志读取过来记录到从服务器本地文件,然后SQL线程会读取relay-log日志的内容并应用到从服务器,从而使从服务器和主服务器的数据保持一致。

它的作用可以参考如下图,从图片中可以看出,它是一个中介临时的日志文件,用于存储从master节点同步过来的binlog日志内容,它里面的内容和master节点的binlog日志里面的内容是一致的。然后slave从节点从这个relaylog日志文件中读取数据应用到数据库中,来实现数据的主从复制。

如下所示:

复制代码
# Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA

#
# The MySQL  Server configuration file.
#
# For explanations see
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html

[mysqld]
pid-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock
datadir         = /var/lib/mysql
secure-file-priv= NULL

# Custom config should go here
!includedir /etc/mysql/conf.d/

# 设置server_id,注意要唯一
server-id=101   
# 开启二进制日志功能,以备Slave作为其它Slave的Master时使用
log-bin=slave1-bin   
# relay_log配置中继日志
relay_log=/var/lib/mysql/relay.log  
read_only=1  # 设置为只读,该项如果不设置,表示slave可读可写
replicate-do-db=nacos_config
复制代码

注意:一定要加上replicate-do-db,否则后面会报错:Last_Error: Error 'Unknown database,后面会讲到。

3、重启mysql-slave1容器

docker restart mysql-slave1

其余两个从容器进行相同操作

mysql-slave2

vim ~/mysql-slave2/conf/my.cnf

配置

server-id=102  
log-bin=slave2-bin   
relay_log=/var/lib/mysql/slave2-relay.log  
read_only=1
replicate-do-db=nacos_config

重启:

docker restart mysql-slave2

mysql-slave3

vim ~/mysql-slave3/conf/my.cnf

配置

server-id=103  
log-bin=slave3-bin   
relay_log=/var/lib/mysql/slave3-relay.log  
read_only=1
replicate-do-db=nacos_config

重启:

docker restart mysql-slave3

 

五、创建用户并授权

在Master数据库创建数据同步用户,授予用户 slave REPLICATION SLAVE权限和REPLICATION CLIENT权限,用于在主从库之间同步数据。

1、进入mysql-master容器

docker exec -it mysql-master bash

2、登录mysql-master

mysql -uroot -p123456

3、创建slave用户

create user 'slave'@'%' IDENTIFIED WITH mysql_native_password BY 'slave';

4、授予slave用户REPLICATION SLAVE权限和REPLICATION CLIENT权限

GRANT REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'slave'@'%';

5、刷新

flush privileges;

6、查看权限

SHOW GRANTS FOR 'slave'@'%';

结果

复制代码
mysql> SHOW GRANTS FOR 'slave'@'%';
+-------------------------------------------------------------------+
| Grants for slave@%                                                |
+-------------------------------------------------------------------+
| GRANT REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO `slave`@`%` |
+-------------------------------------------------------------------+
1 row in set (0.00 sec)
复制代码

表示授权成功!

7、进入mysql-slave容器,以slave账号连接mysql-master。

复制代码
[root@xxx ~]# docker exec -it mysql-slave1 bash
root@7f7b489358dc:/# mysql -h192.172.0.30 -uslave -pslave
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 35
Server version: 8.0.26 MySQL Community Server - GPL

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 
复制代码

说明从服务器通过账号slave,密码slave可以连接mysql-master容器。

8、查看Master状态

show master status;

结果如下:

mysql> show master status;
+-------------------+----------+--------------+-------------------------------------------------+-------------------+
| File              | Position | Binlog_Do_DB | Binlog_Ignore_DB                                | Executed_Gtid_Set |
+-------------------+----------+--------------+-------------------------------------------------+-------------------+
| master-bin.000001 |      848 |              | information_schema,mysql,performance_schema,sys |                   |
+-------------------+----------+--------------+-------------------------------------------------+-------------------+
1 row in set (0.00 sec)

记住File和Position,后面需要用到。此时一定不要操作Master库,否则将会引起Master状态的变化,File和Position字段也将会进行变化。

六、开启主从复制

进入到mysql-slave容器的mysql客户端,执行如下命令:

注:mysqld 是 MySQL 的主程序,服务器端。mysql 是 MySQL 的命令行工具,客户端。

1、进入mysql-slave1容器

docker exec -it mysql-slave1 bash

2、登录

mysql -uroot -p123456

3、执行如下命令

在进行mysql主从复制配置时,change master用于配置和改变slave服务器用于连接master服务器的参数,以便slave服务器读取master服务器的binlog以及slave服务器的relay log,同时更新master.info和relay-log.info信息。

注意:执行该语句之前,从服务器上如果IO线程和SQL线程已经启动,需要先停止,执行stop slave命令。

复制代码
change master to master_host='192.172.0.30', 
 master_user='slave', 
 master_password='slave', 
 master_port=3306, 
 master_log_file='master-bin.000001', 
 master_log_pos=848, 
 master_connect_retry=30;
复制代码

master_log_pos 此参数决定从库复制主库binlog的起始位置。

执行时放在一行执行

change master to master_host='192.172.0.30', master_user='slave', master_password='slave', master_port=3306, master_log_file='master-bin.000001', master_log_pos=848, master_connect_retry=30;

命令说明:

4、查看主从同步状态

复制代码
mysql> show slave status \G;
*************************** 1. row ***************************
               Slave_IO_State: 
                  Master_Host: 192.172.0.30
                  Master_User: slave
                  Master_Port: 3306
                Connect_Retry: 30
              Master_Log_File: master-bin.000001
          Read_Master_Log_Pos: 681
               Relay_Log_File: relay.000001
                Relay_Log_Pos: 4
        Relay_Master_Log_File: master-bin.000001
             Slave_IO_Running: No
            Slave_SQL_Running: No
              Replicate_Do_DB: 
          Replicate_Ignore_DB: 
           Replicate_Do_Table: 
       Replicate_Ignore_Table: 
      Replicate_Wild_Do_Table: 
  Replicate_Wild_Ignore_Table: 
                   Last_Errno: 0
                   Last_Error: 
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 681
              Relay_Log_Space: 156
              Until_Condition: None
               Until_Log_File: 
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File: 
           Master_SSL_CA_Path: 
              Master_SSL_Cert: 
            Master_SSL_Cipher: 
               Master_SSL_Key: 
        Seconds_Behind_Master: NULL
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error: 
               Last_SQL_Errno: 0
               Last_SQL_Error: 
  Replicate_Ignore_Server_Ids: 
             Master_Server_Id: 0
                  Master_UUID: 
             Master_Info_File: mysql.slave_master_info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: 
           Master_Retry_Count: 86400
                  Master_Bind: 
      Last_IO_Error_Timestamp: 
     Last_SQL_Error_Timestamp: 
               Master_SSL_Crl: 
           Master_SSL_Crlpath: 
           Retrieved_Gtid_Set: 
            Executed_Gtid_Set: 
                Auto_Position: 0
         Replicate_Rewrite_DB: 
                 Channel_Name: 
           Master_TLS_Version: 
       Master_public_key_path: 
        Get_master_public_key: 0
            Network_Namespace: 
1 row in set, 1 warning (0.00 sec)

ERROR: 
No query specified
复制代码

mysql replication 中slave机器上有两个关键的进程,死一个都不行,一个是slave_sql_running,一个是Slave_IO_Running,一个负责与主机的io通信,一个负责自己的slave mysql进程。Slave_IO_Running: no 表示从主库读取数据的IO不通。

如果Slave_SQL_Running:显示为No,请检查宿主机~/mysql-master/data/auto.cnf 与~/mysql-slave/data/auto.cnf 是否相同,若相同,请根据容器中mysql命令select uuid();进行修改。

查看~/mysql-master/data/auto.cnf 

[root@xxx ~]# cat ~/mysql-master/data/auto.cnf
[auto]
server-uuid=fdef6cc7-0a2a-11ed-a3d3-0242c0ac001e

查看~/mysql-slave/data/auto.cnf

[root@xxx ~]# cat ~/mysql-slave/data/auto.cnf
[auto]
server-uuid=9eadc9d0-0a2b-11ed-8fc7-0242c0ac001f

发现不同。

如果不同,则执行如下命令

复制代码
mysql> stop slave;
Query OK, 0 rows affected, 2 warnings (0.00 sec)

mysql> SET GLOBAL SQL_SLAVE_SKIP_COUNTER=1;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> START SLAVE; 
Query OK, 0 rows affected, 1 warning (0.01 sec)
复制代码

start slave表示开启主从复制,

再次查看主从同步状态

mysql> show slave status\G 
*************************** 1. row ***************************
               Slave_IO_State: Waiting for source to send event
                  Master_Host: 192.172.0.30
                  Master_User: slave
                  Master_Port: 3306
                Connect_Retry: 30
              Master_Log_File: master-bin.000001
          Read_Master_Log_Pos: 848
               Relay_Log_File: relay.000002
                Relay_Log_Pos: 325
        Relay_Master_Log_File: master-bin.000001
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB: nacos_config
          Replicate_Ignore_DB: 
           Replicate_Do_Table: 
       Replicate_Ignore_Table: 
      Replicate_Wild_Do_Table: 
  Replicate_Wild_Ignore_Table: 
                   Last_Errno: 0
                   Last_Error: 
                 Skip_Counter: 1
          Exec_Master_Log_Pos: 848
              Relay_Log_Space: 524
              Until_Condition: None
               Until_Log_File: 
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File: 
           Master_SSL_CA_Path: 
              Master_SSL_Cert: 
            Master_SSL_Cipher: 
               Master_SSL_Key: 
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error: 
               Last_SQL_Errno: 0
               Last_SQL_Error: 
  Replicate_Ignore_Server_Ids: 
             Master_Server_Id: 100
                  Master_UUID: 46177dae-c94d-11ed-99e6-0242c0ac001e
             Master_Info_File: mysql.slave_master_info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Replica has read all relay log; waiting for more updates
           Master_Retry_Count: 86400
                  Master_Bind: 
      Last_IO_Error_Timestamp: 
     Last_SQL_Error_Timestamp: 
               Master_SSL_Crl: 
           Master_SSL_Crlpath: 
           Retrieved_Gtid_Set: 
            Executed_Gtid_Set: 
                Auto_Position: 0
         Replicate_Rewrite_DB: 
                 Channel_Name: 
           Master_TLS_Version: 
       Master_public_key_path: 
        Get_master_public_key: 0
            Network_Namespace: 
1 row in set, 1 warning (0.00 sec)

此时如果Slave_IO_State: Waiting for source to send event,且Slave_IO_Running和Slave_SQL_Running都为YES,表示主从复制成功.

其他两个从容器进行类似操作

mysql-slave2

进入容器

docker exec -it mysql-slave2 bash

执行如下命令

change master to master_host='192.172.0.30', master_user='slave', master_password='slave', master_port=3306, master_log_file='master-bin.000001', master_log_pos=848, master_connect_retry=30;

查看主从同步状态

show slave status \G;

执行如下命令

mysql> stop slave;
Query OK, 0 rows affected, 2 warnings (0.00 sec)

mysql> SET GLOBAL SQL_SLAVE_SKIP_COUNTER=1;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> START SLAVE; 
Query OK, 0 rows affected, 1 warning (0.01 sec)

mysql-slave3

进入容器

docker exec -it mysql-slave3 bash

执行如下命令

change master to master_host='192.172.0.30', master_user='slave', master_password='slave', master_port=3306, master_log_file='master-bin.000001', master_log_pos=848, master_connect_retry=30;

查看主从同步状态

show slave status \G;

执行如下命令

mysql> stop slave;
Query OK, 0 rows affected, 2 warnings (0.00 sec)

mysql> SET GLOBAL SQL_SLAVE_SKIP_COUNTER=1;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> START SLAVE; 
Query OK, 0 rows affected, 1 warning (0.01 sec)

 

七、报错:Last_Error: Error 'Unknown database

本地电脑中navicat登录主容器和从容器

主容器:

此时主容器中有四个库

1、在navicate中执行如下sql语句

复制代码
CREATE DATABASE nacos_config;
USE nacos_config;

CREATE TABLE `config_info` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` varchar(255) NOT NULL COMMENT 'data_id',
  `group_id` varchar(255) DEFAULT NULL,
  `content` longtext NOT NULL COMMENT 'content',
  `md5` varchar(32) DEFAULT NULL COMMENT 'md5',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  `src_user` text COMMENT 'source user',
  `src_ip` varchar(50) DEFAULT NULL COMMENT 'source ip',
  `app_name` varchar(128) DEFAULT NULL,
  `tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段',
  `c_desc` varchar(256) DEFAULT NULL,
  `c_use` varchar(64) DEFAULT NULL,
  `effect` varchar(64) DEFAULT NULL,
  `type` varchar(64) DEFAULT NULL,
  `c_schema` text,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_configinfo_datagrouptenant` (`data_id`,`group_id`,`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info';


CREATE TABLE `config_info_aggr` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` varchar(255) NOT NULL COMMENT 'data_id',
  `group_id` varchar(255) NOT NULL COMMENT 'group_id',
  `datum_id` varchar(255) NOT NULL COMMENT 'datum_id',
  `content` longtext NOT NULL COMMENT '内容',
  `gmt_modified` datetime NOT NULL COMMENT '修改时间',
  `app_name` varchar(128) DEFAULT NULL,
  `tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_configinfoaggr_datagrouptenantdatum` (`data_id`,`group_id`,`tenant_id`,`datum_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='增加租户字段';


CREATE TABLE `config_info_beta` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` varchar(255) NOT NULL COMMENT 'data_id',
  `group_id` varchar(128) NOT NULL COMMENT 'group_id',
  `app_name` varchar(128) DEFAULT NULL COMMENT 'app_name',
  `content` longtext NOT NULL COMMENT 'content',
  `beta_ips` varchar(1024) DEFAULT NULL COMMENT 'betaIps',
  `md5` varchar(32) DEFAULT NULL COMMENT 'md5',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  `src_user` text COMMENT 'source user',
  `src_ip` varchar(50) DEFAULT NULL COMMENT 'source ip',
  `tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_configinfobeta_datagrouptenant` (`data_id`,`group_id`,`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info_beta';


CREATE TABLE `config_info_tag` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` varchar(255) NOT NULL COMMENT 'data_id',
  `group_id` varchar(128) NOT NULL COMMENT 'group_id',
  `tenant_id` varchar(128) DEFAULT '' COMMENT 'tenant_id',
  `tag_id` varchar(128) NOT NULL COMMENT 'tag_id',
  `app_name` varchar(128) DEFAULT NULL COMMENT 'app_name',
  `content` longtext NOT NULL COMMENT 'content',
  `md5` varchar(32) DEFAULT NULL COMMENT 'md5',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  `src_user` text COMMENT 'source user',
  `src_ip` varchar(50) DEFAULT NULL COMMENT 'source ip',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_configinfotag_datagrouptenanttag` (`data_id`,`group_id`,`tenant_id`,`tag_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info_tag';


CREATE TABLE `config_tags_relation` (
  `id` bigint(20) NOT NULL COMMENT 'id',
  `tag_name` varchar(128) NOT NULL COMMENT 'tag_name',
  `tag_type` varchar(64) DEFAULT NULL COMMENT 'tag_type',
  `data_id` varchar(255) NOT NULL COMMENT 'data_id',
  `group_id` varchar(128) NOT NULL COMMENT 'group_id',
  `tenant_id` varchar(128) DEFAULT '' COMMENT 'tenant_id',
  `nid` bigint(20) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`nid`),
  UNIQUE KEY `uk_configtagrelation_configidtag` (`id`,`tag_name`,`tag_type`),
  KEY `idx_tenant_id` (`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_tag_relation';


CREATE TABLE `group_capacity` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `group_id` varchar(128) NOT NULL DEFAULT '' COMMENT 'Group ID,空字符表示整个集群',
  `quota` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '配额,0表示使用默认值',
  `usage` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '使用量',
  `max_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '单个配置大小上限,单位为字节,0表示使用默认值',
  `max_aggr_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '聚合子配置最大个数,,0表示使用默认值',
  `max_aggr_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '单个聚合数据的子配置大小上限,单位为字节,0表示使用默认值',
  `max_history_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '最大变更历史数量',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_group_id` (`group_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='集群、各Group容量信息表';


CREATE TABLE `his_config_info` (
  `id` bigint(64) unsigned NOT NULL,
  `nid` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `data_id` varchar(255) NOT NULL,
  `group_id` varchar(128) NOT NULL,
  `app_name` varchar(128) DEFAULT NULL COMMENT 'app_name',
  `content` longtext NOT NULL,
  `md5` varchar(32) DEFAULT NULL,
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `src_user` text,
  `src_ip` varchar(50) DEFAULT NULL,
  `op_type` char(10) DEFAULT NULL,
  `tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段',
  PRIMARY KEY (`nid`),
  KEY `idx_gmt_create` (`gmt_create`),
  KEY `idx_gmt_modified` (`gmt_modified`),
  KEY `idx_did` (`data_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='多租户改造';



CREATE TABLE `tenant_capacity` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `tenant_id` varchar(128) NOT NULL DEFAULT '' COMMENT 'Tenant ID',
  `quota` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '配额,0表示使用默认值',
  `usage` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '使用量',
  `max_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '单个配置大小上限,单位为字节,0表示使用默认值',
  `max_aggr_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '聚合子配置最大个数',
  `max_aggr_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '单个聚合数据的子配置大小上限,单位为字节,0表示使用默认值',
  `max_history_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '最大变更历史数量',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_tenant_id` (`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='租户容量信息表';


CREATE TABLE `tenant_info` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `kp` varchar(128) NOT NULL COMMENT 'kp',
  `tenant_id` varchar(128) default '' COMMENT 'tenant_id',
  `tenant_name` varchar(128) default '' COMMENT 'tenant_name',
  `tenant_desc` varchar(256) DEFAULT NULL COMMENT 'tenant_desc',
  `create_source` varchar(32) DEFAULT NULL COMMENT 'create_source',
  `gmt_create` bigint(20) NOT NULL COMMENT '创建时间',
  `gmt_modified` bigint(20) NOT NULL COMMENT '修改时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_tenant_info_kptenantid` (`kp`,`tenant_id`),
  KEY `idx_tenant_id` (`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='tenant_info';

CREATE TABLE `users` (
    `username` varchar(50) NOT NULL PRIMARY KEY,
    `password` varchar(500) NOT NULL,
    `enabled` boolean NOT NULL
);

CREATE TABLE `roles` (
    `username` varchar(50) NOT NULL,
    `role` varchar(50) NOT NULL,
    UNIQUE INDEX `idx_user_role` (`username` ASC, `role` ASC) USING BTREE
);

CREATE TABLE `permissions` (
    `role` varchar(50) NOT NULL,
    `resource` varchar(255) NOT NULL,
    `action` varchar(8) NOT NULL,
    UNIQUE INDEX `uk_role_permission` (`role`,`resource`,`action`) USING BTREE
);

INSERT INTO users (username, password, enabled) VALUES ('nacos', '$2a$10$EuWPZHzz32dJN7jexM34MOeYirDdFAZm2kuWj7VEOJhhZkDrxfvUu', TRUE);

INSERT INTO roles (username, role) VALUES ('nacos', 'ROLE_ADMIN');
复制代码

主容器的数据库如下:

2、此时查看从容器的数据库,发现同步没有成功,仍然是四个库

此时进入从容器查看主从同步状态

复制代码
mysql> show slave status \G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for source to send event
                  Master_Host: 192.172.0.30
                  Master_User: slave
                  Master_Port: 3306
                Connect_Retry: 30
              Master_Log_File: master-bin.000001
          Read_Master_Log_Pos: 12537
               Relay_Log_File: relay.000002
                Relay_Log_Pos: 534
        Relay_Master_Log_File: master-bin.000001
             Slave_IO_Running: Yes
            Slave_SQL_Running: No
              Replicate_Do_DB: nacos_config
          Replicate_Ignore_DB: 
           Replicate_Do_Table: 
       Replicate_Ignore_Table: 
      Replicate_Wild_Do_Table: 
  Replicate_Wild_Ignore_Table: 
                   Last_Errno: 1049
                   Last_Error: Error 'Unknown database 'nacos_config'' on query. Default database: 'nacos_config'. Query: 'CREATE TABLE `config_info` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` varchar(255) NOT NULL COMMENT 'data_id',
  `group_id` varchar(255) DEFAULT NULL,
  `content` longtext NOT NULL COMMENT 'content',
  `md5` varchar(32) DEFAULT NULL COMMENT 'md5',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  `src_user` text COMMENT 'source user',
  `src_ip` varchar(50) DEFAULT NULL COMMENT 'source ip',
  `app_name` varchar(128) DEFAULT NULL,
  `tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段',
  `c_desc` varchar(256) DEFAULT NULL,
  `c_use` varchar(64) DEFAULT NULL,
  `effect` varchar(64) DEFAULT NULL,
  `type` varchar(64) DEFAULT NULL,
  `c_schema` text,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_configinfo_datagrouptenant` (`data_id`,`group_id`,`tenant_id`)
) 
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 1057
              Relay_Log_Space: 12213
              Until_Condition: None
               Until_Log_File: 
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File: 
           Master_SSL_CA_Path: 
              Master_SSL_Cert: 
            Master_SSL_Cipher: 
               Master_SSL_Key: 
        Seconds_Behind_Master: NULL
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error: 
               Last_SQL_Errno: 1049
               Last_SQL_Error: Error 'Unknown database 'nacos_config'' on query. Default database: 'nacos_config'. Query: 'CREATE TABLE `config_info` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` varchar(255) NOT NULL COMMENT 'data_id',
  `group_id` varchar(255) DEFAULT NULL,
  `content` longtext NOT NULL COMMENT 'content',
  `md5` varchar(32) DEFAULT NULL COMMENT 'md5',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  `src_user` text COMMENT 'source user',
  `src_ip` varchar(50) DEFAULT NULL COMMENT 'source ip',
  `app_name` varchar(128) DEFAULT NULL,
  `tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段',
  `c_desc` varchar(256) DEFAULT NULL,
  `c_use` varchar(64) DEFAULT NULL,
  `effect` varchar(64) DEFAULT NULL,
  `type` varchar(64) DEFAULT NULL,
  `c_schema` text,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_configinfo_datagrouptenant` (`data_id`,`group_id`,`tenant_id`)
) 
  Replicate_Ignore_Server_Ids: 
             Master_Server_Id: 100
                  Master_UUID: 88e25bde-c942-11ed-ab5f-0242c0ac001e
             Master_Info_File: mysql.slave_master_info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: 
           Master_Retry_Count: 86400
                  Master_Bind: 
      Last_IO_Error_Timestamp: 
     Last_SQL_Error_Timestamp: 230323 14:25:52
               Master_SSL_Crl: 
           Master_SSL_Crlpath: 
           Retrieved_Gtid_Set: 
            Executed_Gtid_Set: 
                Auto_Position: 0
         Replicate_Rewrite_DB: 
                 Channel_Name: 
           Master_TLS_Version: 
       Master_public_key_path: 
        Get_master_public_key: 0
            Network_Namespace: 
1 row in set, 1 warning (0.01 sec)

ERROR: 
No query specified
复制代码

3、我们先在三个从容器中创建nacos_config数据库

CREATE DATABASE nacos_config;

如下所示:

此时nacos_config库中没有表。

4、进入mysql-slave1容器,停掉从库的slave

stop slave;

再执行

start slave;

此时发现从数据库中表如下:

其他两个从容器进行相同操作。

修改主容器nacos_config数据库中的users表中的数据:

update users set enabled = 2 where username='nacos';

查看三个从容器中users表的数据

 说明同步成功!

标签:COMMENT,主从复制,NULL,mysql8,DEFAULT,master,mysql,一主三,id
From: https://www.cnblogs.com/zwh0910/p/17247296.html

相关文章