I'm trying to import multiple json files into different collections in my mongo database but only the last imported collection is kept.
This is my docker-compose.yml:
version: "3.7"
services:
api:
build: .
restart: always
ports:
- 8080:8080
depends_on:
- mongo-seed
mongo-seed:
build: ./mongo
depends_on:
- mongo_db
mongo_db:
image: "mongo:4.4.3"
restart: always
environment:
- MONGO_INITDB_DATABASE="mongo_db"
ports:
- 27017:27017
And the mongo-seed Dockerfile:
FROM mongo
COPY ./data/users.json /users.json
CMD mongoimport --drop --host mongo_db --db aada_backend --collection users --type json --file /users.json --jsonArray
COPY ./data/headphones.json /headphones.json
CMD mongoimport --drop --host mongo_db --db aada_backend --collection headphones --type json --file /headphones.json --jsonArray
COPY ./data/earbuds.json earbuds.json
CMD mongoimport --drop --host mongo_db --db aada_backend --collection earbuds --type json --file /earbuds.json --jsonArray
I couldn't find anything online about how to import multiple collections into one database, how can I do this?
CodePudding user response:
This happens because you cannot have more than one CMD instruction in the Dockerfile. When you do, only the last one will be executed, this is by design. What you can do within you seed container -
- copy the jsons to the seed container
- copy a shell script containing mongoimport commands to the seed container
- make CMD execute this script.
For example:
FROM mongo
WORKDIR /jsondata
COPY ./jsondata/ .
COPY ./seed.sh .
RUN chmod x seed.sh
CMD ["sh", "-c", "/jsondata/seed.sh"]
then in the docker-compose.yaml you can have it configured this way:
version: "3.8"
services:
mongo_db:
image: mongo
ports:
- 27017:27017
mongo-seed:
build: .
depends_on:
- mongo_db