5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

docker-composeでMongoDBのレプリカセットを作る

Last updated at Posted at 2021-05-14

下準備

Dockerで動かすために、ディレクトリを作成します。

mkdir -p primary/data/db
mkdir -p secondary/data/db

次に、初期化スクリプトを作成します。

mkdir init
touch init/init.js
init.js
rs.initiate({
  _id: 'rs0',
  members: [
    {
      _id: 0,
      host: "mongodb-primary:27017",
      priority: 100
    },
    {
      _id: 1,
      host: "mongodb-secondary:27017",
      priority: 10
    },
    {
      _id: 2,
      host: "mongodb-arbiter:27017",
      arbiterOnly: true
    }
  ],
});

priorityを設定することで、常に指定したコンテナをプライマリーに設定することができます。

docker-compose.yamlを書く

services.[name].commandmongodの引数を入れます。
ホストのmongodと衝突するのを防ぐために、ポートを27018にしています。適宜読み替えてください。

docker-compose.yaml
version: '3'
services: 
  mongodb-primary:
    image: mongo:4.4
    command:
      - --replSet
      - rs0
    volumes:
      - ./primary/data/db:/data/db
      - ./init:/docker-entrypoint-initdb.d:ro
    expose:
      - 27017
    ports:
      - 27018:27017
    restart: always

  mongodb-secondary:
    image: mongo:4.4
    command: 
      - --replSet
      - rs0
    volumes:
      - ./secondary/data/db:/data/db
    expose:
      - 27017
    restart: always

  mongodb-arbiter:
    image: mongo:4.4
    command:
      - --replSet
      - rs0
    expose:
      - 27017
    restart: always

起動

docker-compose up -d
5
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?