mongodbdocker-composeconfigreplicasetrs

Implement docker mongodb replica set config settings inside .yml file


I have set a MongoDB replica set which is running properly. But I want to run the config settings inside the .yml, and not initiating inside a replica set node.

by config settings I mean:

1.

config = {
  "_id": "comments",
  "members": [
    {
      "_id": 0,
      "host": "node1:27017"
    },
    {
      "_id": 1,
      "host": "node2:27017"
    },
    {
      "_id": 2,
      "host": "node3:27017"
    }
  ]
}

and the below:

2.

rs.initiate(config)

Solution

  • So i figured out a way, hope it helps.Below i will post my .yml file, rsinit file and rs.sh file, all the file should be placed on the same location in order to work, rest all config are written anyways.

    .yml file:

    version: '3.7' services: mongo1: hostname: mongo1 container_name: localmongo1 image: mongo expose: - 27017 ports: - 27017:27017 restart: always entrypoint: ["/usr/bin/mongod", "--bind_ip_all", "--replSet", "rs0"] # volumes: # - /data/db/mongotest:/data/db # This is where your volume will persist. e.g. VOLUME-DIR = ./volumes/mongodb

    mongo2: hostname: mongo2 container_name: localmongo2 image: mongo expose: - 27017 ports: - 27018:27017 restart: always entrypoint: ["/usr/bin/mongod", "--bind_ip_all", "--replSet", "rs0"]

    mongo3: hostname: mongo3 container_name: localmongo3 image: mongo expose: - 27017 ports: - 27019:27017 restart: always entrypoint: ["/usr/bin/mongod", "--bind_ip_all", "--replSet", "rs0"]

    rsinit: build: context: . dockerfile: rsinit depends_on: - mongo1 - mongo2 - mongo3 entrypoint: ["sh", "-c", "rs.sh"]

    rsinit(normal text file):

    FROM mongo

    ADD rs.sh /usr/local/bin/

    RUN chmod +x /usr/local/bin/rs.sh

    rs.sh file:

    !/bin/bash

    echo "prepare rs initiating"

    check_db_status() { mongo1=$(mongo --host mongo1 --port 27017 --eval "db.stats().ok" | tail -n1 | grep -E '(^|\s)1($|\s)') mongo2=$(mongo --host mongo2 --port 27017 --eval "db.stats().ok" | tail -n1 | grep -E '(^|\s)1($|\s)') mongo3=$(mongo --host mongo3 --port 27017 --eval "db.stats().ok" | tail -n1 | grep -E '(^|\s)1($|\s)') if [[ $mongo1 == 1 ]] && [[ $mongo2 == 1 ]] && [[ $mongo3 == 1 ]]; then init_rs else check_db_status fi }

    init_rs() { ret=$(mongo --host mongo1 --port 27017 --eval "rs.initiate({ _id: 'rs0', members: [{ _id: 0, host: 'mongo1:27017' }, { _id: 1, host: 'mongo2:27017' }, { _id: 2, host: 'mongo3:27017' } ] })" > /dev/null 2>&1) }

    check_db_status > /dev/null 2>&1

    echo "rs initiating finished" exit 0