スポンサーリンク

【MongoDB】docker-composeでレプリカセット起動

Docker

本記事ではDocker-composeを使用しMongoDBをレプリカセットで起動する方法について説明します。

スポンサーリンク

Docker Desktopをインストール

下記URLからDockerデスクトップをインストールします。

Windows
Get started with Docker for Windows. This guide covers system requirements, where to download, and instructions on how to install and update.

docker-compose.ymlを作成

docker-compose.yml(docker-composeの設定ファイル)を作成します。
※mongo{1~3}.confは後に説明します。

docker-compose.yml

version: "3.7"
services:
    mongo1:
      # MongoDB v7.0.4 イメージを使用
      image: mongo:7.0.4
      ports:
        - 27017:27017
      container_name: mongo1
      hostname: mongo1
      # 設定ファイルを/etc/mongod.confにバインド
      volumes:
        - ./mongo1.conf:/etc/mongod.conf
      # バインドした設定ファイルを起動時に読み込み
      entrypoint: [ "mongod", "--config", "/etc/mongod.conf" ]
      networks:
        - mongo-network
    mongo2:
      image: mongo:7.0.4
      ports:
        - 27018:27018
      container_name: mongo2
      hostname: mongo2
      volumes:
        - ./mongo2.conf:/etc/mongod.conf
      entrypoint: [ "mongod", "--config", "/etc/mongod.conf" ]
      networks:
        - mongo-network
    mongo3:
      image: mongo:7.0.4
      ports:
        - 27019:27019
      container_name: mongo3
      hostname: mongo3
      volumes:
        - ./mongo3.conf:/etc/mongod.conf
      entrypoint: [ "mongod", "--config", "/etc/mongod.conf" ]
      networks:
        - mongo-network
networks:
    mongo-network:

Mongo設定ファイル(mongo{1~3}.conf)を作成

Mongo設定ファイルではレプリカセット名バインドIP設定ポート設定のみを記載しています。
※1~3はport設定以外は同じです。
 ポートはmongo1を27017とし27017~17019まで連番になるようにしています。

mongo1.conf

replication:
  # レプリカセット名にrs0を指定
  replSetName: "rs0"
net:
  # バインドIP設定
  bindIpAll: true
  # 起動ポート設定
  port: 27017

mongo2.conf

replication:
  replSetName: "rs0"
net:
  bindIpAll: true
  port: 27018

mongo3.conf

replication:
  replSetName: "rs0"
net:
  bindIpAll: true
  port: 27019

docker-composeを起動

docker-compose.ymlと各Mongo設定の作成が完了したので、
docker-composeを起動します。
docker-compose up コマンドを実行しmongo1~3のdockerコンテナを起動します。
※バックグラウンドで実行する場合はdocker-compose up -d で起動します。

> docker-compose up
time="2023-12-18T14:04:39+09:00" level=warning msg="Found orphan containers ([mongo]) for this project. If you removed or renamed this service in your compose file, you can run this command with the --remove-orphans flag to clean it up."
[+] Running 3/0
 ✔ Container mongo2  Created                                                                                                                          0.0s 
 ✔ Container mongo1  Created                                                                                                                          0.0s 
 ✔ Container mongo3  Created                                                                                                                          0.0s 
Attaching to mongo1, mongo2, mongo3
mongo1  | {"t":{"$date":"2023-12-18T05:04:40.464+00:00"},"s":"I",  "c":"CONTROL",  "id":23285,   "ctx":"main","msg":"Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'"}

Mongo1コンテナにアタッチし、レプリカセットを設定

docker exec -it mongo1 /bin/sh コマンドを実行しMongo1コンテナにアタッチします。

> docker exec -it mongo1 /bin/sh
#

mongoshコマンドを実行します。

# mongosh
Current Mongosh Log ID: 657fd460e4caff2fee4b0b9d
Connecting to:          mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.1.1
Using MongoDB:          7.0.4
Using Mongosh:          2.1.1

For mongosh info see: https://docs.mongodb.com/mongodb-shell/


To help improve our products, anonymous usage data is collected and sent to MongoDB periodically (https://www.mongodb.com/legal/privacy-policy).
You can opt-out by running the disableTelemetry() command.

------
   The server generated these startup warnings when booting
   2023-12-18T05:10:40.701+00:00: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem
   2023-12-18T05:10:42.952+00:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
   2023-12-18T05:10:42.953+00:00: You are running this process as the root user, which is not recommended
   2023-12-18T05:10:42.954+00:00: /sys/kernel/mm/transparent_hugepage/enabled is 'always'. We suggest setting it to 'never'
   2023-12-18T05:10:42.954+00:00: vm.max_map_count is too low
------

test> 

レプリカセット設定を直打ちで作成します。

conf = { _id: "rs0", members: [{ _id: 0, host: "mongo1:27017"},{_id: 1, host: "mongo2:27018"},{_id: 2,host:"mongo3:27019"}]}

test> conf = { _id: "rs0", members: [{ _id: 0, host: "mongo1:27017"},{_id: 1, host: "mongo2:27018"},{_id: 2,host:"mongo3:27019"}]}
{
  _id: 'rs0',
  members: [
    { _id: 0, host: 'mongo1:27017' },
    { _id: 1, host: 'mongo2:27018' },
    { _id: 2, host: 'mongo3:27019' }
  ]
}

作成した設定でレプリカセット設定を初期化します。

rs.initiate(conf)

test> rs.initiate(conf)
{ ok: 1 }

ok:1が出力されれば設定は完了です。

レプリカセットの設定確認

最後にレプリカセットの設定を確認します。
rs.status()

rs0 [direct: primary] test> rs.status()
{
  set: 'rs0',
  date: ISODate('2023-12-18T05:23:52.402Z'),
  myState: 1,
  term: Long('1'),
  syncSourceHost: '',
  syncSourceId: -1,
  heartbeatIntervalMillis: Long('2000'),    
  majorityVoteCount: 2,
  writeMajorityCount: 2,
  votingMembersCount: 3,
  writableVotingMembersCount: 3,
  optimes: {
    lastCommittedOpTime: { ts: Timestamp({ t: 1702877025, i: 1 }), t: Long('1') },
    lastCommittedWallTime: ISODate('2023-12-18T05:23:45.528Z'),
    readConcernMajorityOpTime: { ts: Timestamp({ t: 1702877025, i: 1 }), t: Long('1') },
    appliedOpTime: { ts: Timestamp({ t: 1702877025, i: 1 }), t: Long('1') },
    durableOpTime: { ts: Timestamp({ t: 1702877025, i: 1 }), t: Long('1') },
    lastAppliedWallTime: ISODate('2023-12-18T05:23:45.528Z'),
    lastDurableWallTime: ISODate('2023-12-18T05:23:45.528Z')
  },
  lastStableRecoveryTimestamp: Timestamp({ t: 1702877005, i: 1 }),
  electionCandidateMetrics: {
    lastElectionReason: 'electionTimeout',
    lastElectionDate: ISODate('2023-12-18T05:16:45.350Z'),
    electionTerm: Long('1'),
    lastCommittedOpTimeAtElection: { ts: Timestamp({ t: 1702876594, i: 1 }), t: Long('-1') },
    lastSeenOpTimeAtElection: { ts: Timestamp({ t: 1702876594, i: 1 }), t: Long('-1') },
    numVotesNeeded: 2,
    priorityAtElection: 1,
    electionTimeoutMillis: Long('10000'),
    numCatchUpOps: Long('0'),
    newTermStartDate: ISODate('2023-12-18T05:16:45.444Z'),
    wMajorityWriteAvailabilityDate: ISODate('2023-12-18T05:16:46.028Z')
  },
  members: [
    {
      _id: 0,
      name: 'mongo1:27017',
      health: 1,
      state: 1,
      stateStr: 'PRIMARY',
      uptime: 792,
      optime: { ts: Timestamp({ t: 1702877025, i: 1 }), t: Long('1') },
      optimeDate: ISODate('2023-12-18T05:23:45.000Z'),
      lastAppliedWallTime: ISODate('2023-12-18T05:23:45.528Z'),
      lastDurableWallTime: ISODate('2023-12-18T05:23:45.528Z'),
      syncSourceHost: '',
      syncSourceId: -1,
      infoMessage: '',
      electionTime: Timestamp({ t: 1702876605, i: 1 }),
      electionDate: ISODate('2023-12-18T05:16:45.000Z'),
      configVersion: 1,
      configTerm: 1,
      self: true,
      lastHeartbeatMessage: ''
    },
    {
      _id: 1,
      name: 'mongo2:27018',
      health: 1,
      state: 2,
      stateStr: 'SECONDARY',
      uptime: 438,
      optime: { ts: Timestamp({ t: 1702877025, i: 1 }), t: Long('1') },
      optimeDurable: { ts: Timestamp({ t: 1702877025, i: 1 }), t: Long('1') },
      optimeDate: ISODate('2023-12-18T05:23:45.000Z'),
      optimeDurableDate: ISODate('2023-12-18T05:23:45.000Z'),
      lastAppliedWallTime: ISODate('2023-12-18T05:23:45.528Z'),
      lastDurableWallTime: ISODate('2023-12-18T05:23:45.528Z'),
      lastHeartbeat: ISODate('2023-12-18T05:23:51.609Z'),
      lastHeartbeatRecv: ISODate('2023-12-18T05:23:50.574Z'),
      pingMs: Long('0'),
      lastHeartbeatMessage: '',
      syncSourceHost: 'mongo1:27017',
      syncSourceId: 0,
      infoMessage: '',
      configVersion: 1,
      configTerm: 1
    },
    {
      _id: 2,
      name: 'mongo3:27019',
      health: 1,
      state: 2,
      stateStr: 'SECONDARY',
      uptime: 438,
      optime: { ts: Timestamp({ t: 1702877025, i: 1 }), t: Long('1') },
      optimeDurable: { ts: Timestamp({ t: 1702877025, i: 1 }), t: Long('1') },
      optimeDate: ISODate('2023-12-18T05:23:45.000Z'),
      optimeDurableDate: ISODate('2023-12-18T05:23:45.000Z'),
      lastAppliedWallTime: ISODate('2023-12-18T05:23:45.528Z'),
      lastDurableWallTime: ISODate('2023-12-18T05:23:45.528Z'),
      lastHeartbeat: ISODate('2023-12-18T05:23:51.608Z'),
      lastHeartbeatRecv: ISODate('2023-12-18T05:23:50.574Z'),
      pingMs: Long('0'),
      lastHeartbeatMessage: '',
      syncSourceHost: 'mongo1:27017',
      syncSourceId: 0,
      infoMessage: '',
      configVersion: 1,
      configTerm: 1
    }
  ],
  ok: 1,
  '$clusterTime': {
    clusterTime: Timestamp({ t: 1702877025, i: 1 }),
    signature: {
      hash: Binary.createFromBase64('AAAAAAAAAAAAAAAAAAAAAAAAAAA=', 0),
      keyId: Long('0')
    }
  },
  operationTime: Timestamp({ t: 1702877025, i: 1 })
}

以上でレプリカセットの設定確認も完了です。
お疲れ様でした。

タイトルとURLをコピーしました