使用docker-compose部署mongodb集群(一主两从的副本集模式)

本文详细介绍了如何使用docker-compose部署一个MongoDB的主从副本集,包括配置文件、集群初始化、数据读写以及设置数据库访问密码。同时提到了SpringBoot应用连接MongoDB的配置示例。
摘要由CSDN通过智能技术生成

一、部署架构

在这里插入图片描述

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

二、安装

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:

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

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

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> 
  • 你也可以使用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>  

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

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

在这里插入图片描述

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要创建一个MongoDB副本集群,你可以使用Docker来运行多个MongoDB容器。下面是一些步骤: 1. 首先,确保你已经安装了DockerDocker Compose。 2. 创建一个新的目录,并在该目录下创建一个名为`docker-compose.yml`的文件。 3. 在`docker-compose.yml`文件中定义三个MongoDB容器,分别命名为`mongo1`、`mongo2`和`mongo3`。你可以使用以下配置作为参考: ``` version: '3' services: mongo1: image: mongo restart: always ports: - 27017:27017 volumes: - ./data/db1:/data/db command: --replSet rs0 mongo2: image: mongo restart: always ports: - 27018:27017 volumes: - ./data/db2:/data/db command: --replSet rs0 mongo3: image: mongo restart: always ports: - 27019:27017 volumes: - ./data/db3:/data/db command: --replSet rs0 ``` 4. 在每个MongoDB容器中,我们使用`--replSet rs0`参数来指定副本的名称为`rs0`。此外,我们还将每个容器的数据文件夹挂载到主机上的不同目录中,以便数据持久化。 5. 在终端中,切换到包含`docker-compose.yml`文件的目录,并运行以下命令来启动副本集群: ``` docker-compose up -d ``` 这将启动三个MongoDB容器,并将它们连接到一个名为`rs0`的副本集群。 6. 进入其中一个MongoDB容器中,可以使用以下命令: ``` docker exec -it <container_name> bash ``` 在容器内部,使用以下命令来初始化副本集群: ``` mongo rs.initiate() ``` 7. 接下来,你可以添加其他的MongoDB节点到副本集群中。在容器内部,使用以下命令将其他节点添加到副本集群: ``` rs.add("<hostname>:<port>") ``` 其中`<hostname>`是其他MongoDB容器的主机名,`<port>`是该容器上MongoDB实例的端口号。 这样,你就创建了一个基于DockerMongoDB副本集群。你可以通过连接到其中一个容器并使用MongoDB客户端来访问和管理该集群
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天草二十六_简村人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值