当前位置:   article > 正文

使用docker-compose部署mongodb集群(一主两从的副本集模式)_mongocompose连接mongodb数据库主从

mongocompose连接mongodb数据库主从

一、部署架构

在这里插入图片描述

  • 一个主节点,两个从节点。
  • 可以对主节点进行读和写;从节点默认是不能读的,更别说写了(需要你开启读权限)

二、安装

1、docker-compose.yml

主节点暴露端口号,见下映射关系。

version: "3.5"
services:
  mongodb-primary:
    image: mongo:5.0
    command: --bind_ip_all --replSet mongo-replica
    networks:
      mongodb_network:
        aliases: 
          - mongo-1
    volumes:
      - ./data/mongodb1:/data/modelDb
    ports:
      - 27017:27017

  mongodb-secondary-1:
    image: mongo:5.0
    command: --bind_ip_all --replSet mongo-replica
    networks:
      mongodb_network:
        aliases: 
          - mongo-2
    volumes:
      - ./data/mongodb2:/data/modelDb

  mongodb-secondary-2:
    image: mongo:5.0
    command: --bind_ip_all --replSet mongo-replica
    networks:
      mongodb_network:
        aliases: 
          - mongo-3
    volumes:
      - ./data/mongodb3:/data/modelDb


networks:
  mongodb_network:

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

部署成功,容器列表见下
在这里插入图片描述

2、加入集群

进入主节点,初始化副本集,把其他两个从节点加入到集群中。

mongo --host mongo-1:27017 <<EOF
 var cfg = {
   "_id": "mongo-replica",
   "version": 1,
   "members": [
     {
       "_id": 0,
       "host": "mongo-1:27017",
       "priority": 2
     },
     {
       "_id": 1,
       "host": "mongo-2:27017",
       "priority": 1
     },
     {
       "_id": 2,
       "host": "mongo-3:27017",
       "priority": 0
     }
   ]
 };
 rs.initiate(cfg, { force: true });
 rs.reconfig(cfg, { force: true });
 rs.secondaryOk();
 
 rs.status();
 
 db.getMongo().setReadPref('nearest');
 db.getMongo().setSecondaryOk();
EOF
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

3、主节点插入数据,从节点查询到数据

root@fbd4a30d1dbe:/# mongo --host mongo-1:27017
MongoDB shell version v5.0.5
connecting to: mongodb://mongo-1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("4020e958-4681-4374-abdf-a19dacc7b463") }
MongoDB server version: 5.0.5
================
Warning: the "mongo" shell has been superseded by "mongosh",
which delivers improved usability and compatibility.The "mongo" shell has been deprecated and will be removed in
an upcoming release.
For installation instructions, see
https://docs.mongodb.com/mongodb-shell/install/
================
---
The server generated these startup warnings when booting: 
        2023-04-28T09:09:13.958+00:00: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem
        2023-04-28T09:09:14.577+00:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
---
---
        Enable MongoDB's free cloud-based monitoring service, which will then receive and display
        metrics about your deployment (disk utilization, CPU, operation statistics, etc).

        The monitoring data will be available on a MongoDB website with a unique URL accessible to you
        and anyone you share the URL with. MongoDB may use this information to make product
        improvements and to suggest MongoDB products and deployment options to you.

        To enable free monitoring, run the following command: db.enableFreeMonitoring()
        To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---
mongo-replica:PRIMARY> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
mongo-replica:PRIMARY> use testdb
switched to db testdb
mongo-replica:PRIMARY> db.testdb.insert({age:1})
WriteResult({ "nInserted" : 1 })
mongo-replica:PRIMARY> 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 你也可以使用mongodb客户端工具连接主节点,见下图
    在这里插入图片描述
  • 从节点进入容器,可以查询到刚才新增的数据
  • 需要你手动开启db.getMongo().setSecondaryOk(),否则会报错“not master and slaveOk=false”
root@3325ad7f6358:/# mongo --host mongo-3:27017
MongoDB shell version v5.0.5
connecting to: mongodb://mongo-3:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("8408241d-e91c-406e-8434-d2f05ef72402") }
MongoDB server version: 5.0.5
================
Warning: the "mongo" shell has been superseded by "mongosh",
which delivers improved usability and compatibility.The "mongo" shell has been deprecated and will be removed in
an upcoming release.
For installation instructions, see
https://docs.mongodb.com/mongodb-shell/install/
================
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
        https://docs.mongodb.com/
Questions? Try the MongoDB Developer Community Forums
        https://community.mongodb.com
---
The server generated these startup warnings when booting: 
        2023-04-28T09:09:13.958+00:00: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem
        2023-04-28T09:09:14.578+00:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
---
---
        Enable MongoDB's free cloud-based monitoring service, which will then receive and display
        metrics about your deployment (disk utilization, CPU, operation statistics, etc).

        The monitoring data will be available on a MongoDB website with a unique URL accessible to you
        and anyone you share the URL with. MongoDB may use this information to make product
        improvements and to suggest MongoDB products and deployment options to you.

        To enable free monitoring, run the following command: db.enableFreeMonitoring()
        To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---
mongo-replica:SECONDARY> show dbs
uncaught exception: Error: listDatabases failed:{
        "topologyVersion" : {
                "processId" : ObjectId("644b8d39851d74feb84181ab"),
                "counter" : NumberLong(3)
        },
        "ok" : 0,
        "errmsg" : "not master and slaveOk=false",
        "code" : 13435,
        "codeName" : "NotPrimaryNoSecondaryOk",
        "$clusterTime" : {
                "clusterTime" : Timestamp(1682673406, 1),
                "signature" : {
                        "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
                        "keyId" : NumberLong(0)
                }
        },
        "operationTime" : Timestamp(1682673406, 1)
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
Mongo.prototype.getDBs/<@src/mongo/shell/mongo.js:145:19
Mongo.prototype.getDBs@src/mongo/shell/mongo.js:97:12
shellHelper.show@src/mongo/shell/utils.js:956:13
shellHelper@src/mongo/shell/utils.js:838:15
@(shellhelp2):1:1

mongo-replica:SECONDARY> db.getMongo().setSecondaryOk()
mongo-replica:SECONDARY> use testdb
switched to db testdb
mongo-replica:SECONDARY> db.testdb.find()
{ "_id" : ObjectId("644b8ec9d0158b0f63859e0c"), "age" : 1 }
mongo-replica:SECONDARY>  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66

三、设置数据库的访问密码

db.createUser({user:“admin”,pwd:“admin”,roles:[{“role”:“userAdminAnyDatabase”,“db”:“admin”},{“role”:“readWrite”,“db”:“testdb”}]})

新增admin用户,密码为admin。

默认是不用账户和密码的授权。

四、附录

  • 源码地址:git@github.com:zwp201301/mongodb-replset.git
  • spring boot连接mongodb的数据源地址:spring.data.mongodb.uri: mongodb://admin:admin@mongo-1:27017,mongo-2:27017,mongo-3:27017/testdb?replicaSet=mongo-replica&readPreference=secondaryPreferred&connectTimeoutMS=300000

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/407838
推荐阅读
相关标签
  

闽ICP备14008679号