I have a question. I'm starting learn docker. I know how create a container, now I try import data(json) to my container mongo, but I don't know how I can make this. Can you help me and give a simple solution for this? With Docker-compose.
My container - mongo My file - data.json
Thanks!
You can not import JSON simply using docker-compose. you need to place the data in js file and mount the js
file with /docker-entrypoint-initdb.d
When a container is started for the first time it will execute files with extensions
.sh
and.js
that are found in/docker-entrypoint-initdb.d
. Files will be executed in alphabetical order..js
files will be executed by mongo using the database specified by theMONGO_INITDB_DATABASE
variable, if it is present, or test otherwise. You may also switch databases within the.js
script.
mongo Initializing a fresh instance
Example js file:
db = db.getSiblingDB("test");
db.article.drop();
db.article.save( {
title : "this is my title" ,
author : "bob" ,
posted : new Date(1079895594000) ,
pageViews : 5 ,
tags : [ "fun" , "good" , "fun" ] ,
comments : [
{ author :"joe" , text : "this is cool" } ,
{ author :"sam" , text : "this is bad" }
],
other : { foo : 5 }
});
db.article.save( {
title : "this is your title" ,
author : "dave" ,
posted : new Date(4121381470000) ,
pageViews : 7 ,
tags : [ "fun" , "nasty" ] ,
comments : [
{ author :"barbara" , text : "this is interesting" } ,
{ author :"jenny" , text : "i like to play pinball", votes: 10 }
],
other : { bar : 14 }
});
db.article.save( {
title : "this is some other title" ,
author : "jane" ,
posted : new Date(978239834000) ,
pageViews : 6 ,
tags : [ "nasty" , "filthy" ] ,
comments : [
{ author :"will" , text : "i don't like the color" } ,
{ author :"jenny" , text : "can i get that in green?" }
],
other : { bar : 14 }
});
docker-compose
mongo:
image: mongo
container_name: mongo1
environment:
MONGO_INITDB_ROOT_USERNAME: test
MONGO_INITDB_ROOT_PASSWORD: admin
MONGO_INITDB_DATABASE: test
volumes:
- ./init.js:/docker-entrypoint-initdb.d/init.js
ports:
- 27017:27017