使用docker-compose部署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:

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

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
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用docker-compose部署Redis集群的步骤: 1.创建一个目录,例如redis-cluster,并在该目录中创建一个docker-compose.yaml文件。 2.在docker-compose.yaml文件中编写以下内容: ```yaml version: '3' services: redis-1: image: redis:6.0.9 command: redis-server /usr/local/etc/redis/redis.conf volumes: - ./redis.conf:/usr/local/etc/redis/redis.conf ports: - "6379" networks: - redis-cluster redis-2: image: redis:6.0.9 command: redis-server /usr/local/etc/redis/redis.conf volumes: - ./redis.conf:/usr/local/etc/redis/redis.conf ports: - "6380" networks: - redis-cluster redis-3: image: redis:6.0.9 command: redis-server /usr/local/etc/redis/redis.conf volumes: - ./redis.conf:/usr/local/etc/redis/redis.conf ports: - "6381" networks: - redis-cluster networks: redis-cluster: driver: bridge ``` 3.在redis-cluster目录中创建一个redis.conf文件,并将以下内容复制到文件中: ```conf bind 0.0.0.0 port 6379 cluster-enabled yes cluster-config-file nodes.conf cluster-node-timeout 5000 appendonly yes requirepass 1111 masterauth 1111 ``` 4.在终端中导航到redis-cluster目录,并运行以下命令启动Redis集群: ```shell docker-compose up -d ``` 5.使用以下命令进入redis-1容器: ```shell docker exec -it redis-cluster_redis-1_1 /bin/bash ``` 6.在redis-1容器中,使用以下命令创建Redis集群: ```shell redis-cli --cluster create 172.20.0.2:6379 172.20.0.3:6379 172.20.0.4:6379 --cluster-replicas 0 ``` 7.现在,您已经成功地使用docker-compose部署了Redis集群

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值