How to restart an existing MongoDB Docker Container with a new flags to daemon

Viewed 5021

Current State

  • I have a MongoDB instance running on a server without the replication set flag (--replSet)
  • I have some previously stored information on the Database and wish to retain the information

Aim

  • I wish to however restart the container with the --replSet "my-set" flag set for the daemon and keep the previous information intact

Implementation

I am trying to follow along a tutorial for setting replica sets in MongoDB with Docker and trying it out on my local machine.

  1. Create a standard MongoDB Docker container w/o the flag replSet set which represents the current state:

    docker run -d --name mongo_rs --publish 37017:27017 mongo
    
  2. Using the MongoDB Compass I connected to the DB and added some dummy information to a Database called test and collection called players

  3. I stop the container:

    docker container stop mongo_rs
    

From here onwards I wish to add the --replSet "my-set" to the mongo_rs container and configuring the Replica set via the mongo Shell as mentioned in the tutorial. What is the possible solution for achieving it?

2 Answers

Here is a workaround:

1- copy the entrypoint script to your host:

docker cp mongo_rs:/usr/local/bin/docker-entrypoint.sh .

2- edit the script , change the line (last line) exec "$@" to :

mongod --replSet my-mongo-set --port 27017

3- re-copy the script to your container:

docker cp docker-entrypoint.sh mongo_rs:/usr/local/bin/docker-entrypoint.sh

4- start your container:

docker start mongo_rs

Here is my .yml file

version: '3.7'

services:
  node1:
    image: mongo 
    ports:
      - 30001:27017 
    volumes:
      - $HOME/mongoclusterdata/node1:/data/db 
    networks:
      - mongocluster
    command: mongod --replSet comments 
  node2:
    image: mongo
    ports:
      - 30002:27017
    volumes:
      - $HOME/mongoclusterdata/node2:/data/db
    networks:
      - mongocluster
    command: mongod --replSet comments
    depends_on :
      - node1 
  node3:
    image: mongo
    ports:
      - 30003:27017
    volumes:
      - $HOME/mongoclusterdata/node3:/data/db
    networks:
      - mongocluster
    command: mongod --replSet comments
    depends_on :
        - node2 

networks:
  mongocluster:
    driver: bridge 

The volume section has absolute path which is different from the root.Actually docker file creates a self config file on root , so if u have root as a docker-compose install location change it to else where, and now the config file settings would never delete on docker-install up/down.

Related