1. 程式人生 > >使用docker-compose製作mongodb 4 的replica set複製集(可用方案)

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

首先我的環境是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.

後續有時間再補充多機的複製集應用。