使用docker-compose制作mongodb 4 的replica set复制集(可用方案)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/penker_zhao/article/details/84841495

首先我的环境是CentOS 6.9+Docker 1.9.1。所以不能跑version "2"和version "3"的写法。docker-compose.yml写法如下:

  rs0:
    image: mongo:latest
    ports:
      - 37017:27017
    command: mongod --replSet rs
    restart: always
  rs1:
    image: mongo:latest
    ports:
      - 37018:27017
    command: mongod --replSet rs
    restart: always
  rs2:
    image: mongo:latest
    ports:
      - 37019:27017
    command: mongod --replSet rs
    restart: always

然后使用#>docker exec -it --user root 容器ID /bin/bash进入mongodb容器。

使用mongo进入mongodb的命令行界面,使用如下命令>mongo --port 37017 ,建立复制集:

rs0.primary>rs.initiate({_id: "rs",version: 1,members: [{ _id: 0, host : "192.168.30.45:37017" },{ _id: 1, host : "192.168.30.45:37018" },{ _id: 2, host : "192.168.30.45:37019" }]})

创建用户和密码
db.createUser({user: "root",pwd: "123456",roles: [{role: "userAdminAnyDatabase",db:"admin"}]})

具体测试和指南参考这篇文章

https://pacoyang.com/2018/03/08/MongoDB-Replica-Set/

spring boot使用需要设置下面类似的参数

spring:
  data:
    mongodb:
      custom:
        hosts:
          - 10.0.5.1
          - 10.0.5.1
        ports:
          - 27017
          - 27018
        replica-set: mgset-3590061
        username: jancee
        password: abc123
        database: jancee
        authentication-database: admin
        connections-per-host: 20
        min-connections-per-host: 20

关于mongodb replica set的补充,请看mongodb的官方文档说的很清楚,至少三台机器,要么一主两从,要么一主一从一仲裁

The secondaries replicate the primary’s oplog and apply the operations to their data sets such that the secondaries’ data sets reflect the primary’s data set. If the primary is unavailable, an eligible secondary will hold an election to elect itself the new primary. For more information on secondary members, see Replica Set Secondary Members.

Diagram of a 3 member replica set that consists of a primary and two secondaries.

click to enlarge

You may add an extra mongod instance to a replica set as an arbiter. Arbiters do not maintain a data set. The purpose of an arbiter is to maintain a quorum in a replica set by responding to heartbeat and election requests by other replica set members. Because they do not store a data set, arbiters can be a good way to provide replica set quorum functionality with a cheaper resource cost than a fully functional replica set member with a data set. If your replica set has an even number of members, add an arbiter to obtain a majority of votes in an election for primary. Arbiters do not require dedicated hardware. For more information on arbiters, see Replica Set Arbiter.

Diagram of a replica set that consists of a primary, a secondary, and an arbiter.

click to enlarge

An arbiter will always be an arbiter whereas a primary may step down and become a secondary and a secondarymay become the primary during an election.

后续有时间再补充多机的复制集应用。

猜你喜欢

转载自blog.csdn.net/penker_zhao/article/details/84841495