4

As a newbie of Docker, I tried to build a mongoDB Docker container containing some sample data by means of docker-compose.yml in the working directory.

My mongo/Dockerfile contains following code:

FROM mongo:latest
ADD shops.json /home/
RUN mongoimport --db masterdata --collection shops --file /home/shops.json

In the last line, sample data would be imported to mongoDB.

My docker-compose.yml contains the following code:

version: '3'
  services:
    mongo:
    build: mongo
    ports:
    - "27017:27017"

With the configuration above, I tried to build the MongoDB docker container and got error:

Failed: error connecting to db server: no reachable servers 

This problem looks similar with mongoimport Docker Failed: error connecting to the db server: no reachable servers, but I really tried every suggestion given in mongoimport Docker Failed: error connecting to the db server: no reachable servers and am never able to resolve this error.

So anyone can help on this?

Rui
  • 3,454
  • 6
  • 37
  • 70

2 Answers2

2
RUN mkdir -p /opt/acrc/config
COPY *.json /opt/acrc/config/
RUN mongod --fork --logpath=/tmp/mongodb.log && sleep 20 && \
  mongoimport -c=users -d=acrc --mode=upsert --file=/opt/acrc/config/users.json && \
  mongoimport -c=tasks -d=acrc --mode=upsert --file=/opt/acrc/config/tasks.json && \
  mongoimport -c=configs -d=acrc --mode=upsert --file=/opt/acrc/config/configs.json && \
  mongoimport -c=agentGroupConfigs -d=acrc --mode=upsert --file=/opt/acrc/config/agentGroupConfigs.json  
1

The mongo database is not started until you start a container of your image. The Dockerfile just takes care of the files and folders within the image but doesn't start any services.

To import a json into the database, you can write a bash script which will start the mongo services and import the json. You can set this script as entry script for your image.

abskmj
  • 760
  • 3
  • 6
  • 1
    why we need to do docker run if we are build our app using docker-compose here ? – Prabhat Singh Dec 07 '18 at 07:47
  • I meant until a container is started. I have changed my answer. – abskmj Dec 07 '18 at 09:33
  • @abskmj So in that case my way of adding the `RUN mongoimport` in the end of the Dockerfile is kinda wrong? meaning I should run `mongoimport` after installing the mongo container, right? – Rui Dec 07 '18 at 11:11
  • Yes, or you can add it as part of your start script for your docker image. – abskmj Dec 12 '18 at 10:56