Configuring MongoDB replica set from docker-compose

martins picture martins · Jun 30, 2015 · Viewed 7.7k times · Source

I'm using docker-compose to start 3 MongoDB servers which should be in a replica set.

I first start 3 MongoDB servers, then I configure the replica set. This is how I would do the replica set config in a bash script:

mongo --host 127.0.0.1:27017 <<EOF
var cfg = {
    "_id": "rs",
    "version": 1,
    "members": [
        {
            "_id": 0,
            "host": "127.0.0.1:27017",
            "priority": 1
        },

        // snip...

    ]
};
rs.initiate(cfg);
rs.reconfig(cfg)
EOF

Here I'm trying to replicate the configuring of the replica set using docker-compose.

# docker-compose.yml

mongosetup:
  image: mongo:3.0
  links:
    - mongo1:mongo1
  command: echo 'var cfg = { "_id": "rs", "version": 1, "members": [ { "_id": 0, "host": "127.0.0.1:27017", "priority": 1 }, { "_id": 1, "host": "mongo2:27017", "priority": 1 },{ "_id": 2, "host": "mongo2:27017", "priority": 1 } ] }; rs.initiate(cfg);' | mongo mongo1

Unfortunately that creates this error: yaml.scanner.ScannerError: mapping values are not allowed here.

What's the recommended approach? Is it possible to store the cfg object in a separate file that docker-compose reads?

Answer

martins picture martins · Jul 7, 2015

I fixed the problem by putting the config in setup.sh which I called from entrypoint.

mongosetup:
  image: mongo:3.0
  links:
    - mongo1:mongo1
    - mongo2:mongo2
    - mongo3:mongo3
  volumes:
    - ./scripts:/scripts
  entrypoint: [ "/scripts/setup.sh" ]

setup.sh

#!/bin/bash

MONGODB1=`ping -c 1 mongo1 | head -1  | cut -d "(" -f 2 | cut -d ")" -f 1`

mongo --host ${MONGODB1}:27017 <<EOF
   var cfg = {
        "_id": "rs",
        "version": 1,
        "members": [
            {
                "_id": 0,
                "host": "${MONGODB1}:27017",
[cut..]
EOF

I have created a setup with docker-compose that starts 3 MongoDBs in a replica set and ElasticSearch with mongodb-river.

It's available at https://github.com/stabenfeldt/elastic-mongo