0

I have a MongoDb container which is using a single node replica set configured like following code. To run a replica set i need to execute another command on mongoDb shell which is rs.initiate() How to add that command into the container configuration command list so that i do not have to execute that command manually on MongoDb shell ?

 mongodb:
    image: mongo:5.0
    container_name: mongodb
    command: ["--replSet", "rs0", "--bind_ip_all"] # This works but i have to manually go into mongoshell to execute rs.initilize(), i dont want to do that
   # command: ["--replSet", "rs0", "--bind_ip_all","mongo", "rs.initiate()"] # --> Does't work
   # command: ["--replSet", "rs0", "--bind_ip_all","rs.initiate()"]          # --> Does't work
   # command: ["--replSet", "rs0", "--bind_ip_all", "mongo rs.initiate()"]   # --> Does't work

    networks:
      - dev
    ports:
      - 27017:27017
    volumes:
      - ${HOME}/mongodb:/data/db
ATHER
  • 3,254
  • 5
  • 40
  • 63
  • I would also like to not have to exec into the container and run `rs.initiate()` so I'd also like this question answered. One question though Ather, I added this single node rs to my docker-compose file and got it to start but I cannot connect to it with a connection string of `mongodb://localhost:27017/myDB?replicaSet=rs0` How do you connect to it? – Alessandro Nov 09 '21 at 15:37
  • this connection string works for me (Works with MongoDB Compass UI) mongodb://localhost:27017/?replicaSet=rs0&readPreference=primary&appname=MongoDB%20Compass&directConnection=true&ssl=false – ATHER Nov 10 '21 at 18:59

1 Answers1

0

Ok, i am not sure if this is the correct way to solve that problem but, i got that working by using healthcheck feature of Docker. After this change, i do not have to execute rs.initiate() manually

For details please look at docker mongo for single (primary node only) replica set (for development)?

HealthCheck: https://docs.docker.com/engine/reference/builder/#healthcheck

mongodb:
    image: mongo:5.0
    container_name: mongodb
    command: ["--replSet", "rs0", "--bind_ip_all"] 
      - dev
    ports:
      - 27017:27017
    volumes:
      - ${HOME}/mongodb:/data/db
    healthcheck:
      test: test $$(echo "rs.initiate().ok || rs.status().ok" | mongo -u root -p imagiaRoot --quiet) -eq 1
      interval: 10s
      start_period: 30s 
ATHER
  • 3,254
  • 5
  • 40
  • 63