0

This is my Dockerfile:

FROM mongo

WORKDIR /usr/src/app

COPY db /usr/src/app/db

COPY replica.js /usr/src/app/

CMD mongo

The replica.js as follows

rs.initiate();

This is my docker-compose file

mongo_server:
    image: mongo
    hostname: mongo_server.$ENV_NAME
    build:
      context: ./mongo
      dockerfile: Dockerfile
    expose:
      - 27017
    ports:
      - "$MONGO_PORT:27017"
    restart: always
    networks:
      localnet:
        aliases:
          - mongo_server.$ENV_NAME
    command: --replSet $MONGO_REPLICA --bind_ip_all
    volumes:
      - "mongovolume:/data/db"

The problem is if I run successfully docker-compose up. Then I need to run manually two command

docker exec 2b2 sh -c "mongo < /usr/src/app/replica.js" # 2b2 is id of container mongo

and

docker exec 2b2 sh -c "mongorestore --drop -d mydb /usr/src/app/db"

Now the replica is set, the database is restored. My question is could I make it automatically such as moving to entrypoint.sh and call in Dockerfile or setting in docker-compose.yml to reduce manual work?

Steve Lam
  • 979
  • 1
  • 17
  • 40

1 Answers1

0

There is definitely a way by adding another container in your docker-compose file:

mongo_restore:
    image: mongo
    build:
      context: ./mongo
      dockerfile: Dockerfile
    networks:
      localnet:
        aliases:
          - mongo_server.$ENV_NAME
    entrypoint:
      - sh
    command:
      - -c
      - |
        # Step 1: Wait until mongo_server is fully up and running. Please insert your own code to check.
        # Step 2: Execute your restore script but make sure to target mongo_server instead
    volumes:
      - "mongovolume:/data/db"

There might be some syntax errors here and there but the idea is the same as I have used this method in some other projects :)

Nguyen Lam Phuc
  • 1,411
  • 1
  • 7
  • 12
  • What is the difference in creating a new container vs running in `entrypoint.sh` or `setup.js` file in this case? – Steve Lam Feb 03 '20 at 16:11
  • The main difference is that if you use entrypoint.sh, you will need to create a new container whenever you want to update the logic: e.g. copy data from another database. While using another container, you will essentially decouple these logic and it is also easier to debug! – Nguyen Lam Phuc Feb 04 '20 at 01:38