[英]Creating mongodb database and populating it with some data via docker-compose
我有以下腳本並指定了自定義數據庫,但我沒有看到在GUI(指南針)中創建數據庫用戶。 我只看到3個默認數據庫(admin,config,local)。
我已經查看了這個相關的答案,但我需要一個針對我的問題的具體答案。
mongo:
image: mongo:4.0.10
container_name: mongo
restart: always
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: mypass
MONGO_INITDB_DATABASE: mydb
ports:
- 27017:27017
- 27018:27018
- 27019:27019
編輯 - 取得了一些進展,2個問題
增加了量
mongo:
image: mongo:4.0.1r0
container_name: mongo
restart: always
volumes:
- ./assets:/docker-entrypoint-initdb.d/
1.忽略
在assets文件夾中,我有3個文件,我在日志中看到這個,我的文件被忽略了。
/usr/local/bin/docker-entrypoint.sh: ignoring /docker-entrypoint-initdb.d/file1.json
/usr/local/bin/docker-entrypoint.sh: ignoring /docker-entrypoint-initdb.d/file2.json
/usr/local/bin/docker-entrypoint.sh: ignoring /docker-entrypoint-initdb.d/file3.json
我的所有JSON文件如下所示。 (沒有根數組對象?根目錄沒有[]
?)
{ "_id" : { "$oid" : "5d3a9d423b881e4ca04ae8f0" }, "name" : "Human Resource" }
{ "_id" : { "$oid" : "5d3a9d483b881e4ca04ae8f1" }, "name" : "Sales" }
2.未創建默認數據庫。 以下行沒有任何效果。
MONGO_INITDB_DATABASE: mydb
所有文件*.json
擴展名都將被忽略,它應該在*.js
。 查看mongo DB docker hub的文檔
MONGO_INITDB_DATABASE
此變量允許您在
/docker-entrypoint-initdb.d/*.js
指定要用於創建腳本的數據庫的名稱(請參閱下面的初始化新實例)。 MongoDB是“首次使用時創建”的基礎, 因此如果不在JavaScript文件中插入數據,則不會創建數據庫。
初始化一個新實例
當容器第一次啟動時,它將執行擴展名為.sh和.js的文件,這些文件位於
/docker-entrypoint-initdb.d
。 文件將按字母順序執行。 .js文件將由mongo使用MONGO_INITDB_DATABASE
變量指定的數據庫執行(如果存在),否則進行測試。 您也可以在.js腳本中切換數據庫。
你可以看一下這個例子
創建文件夾數據並在其中放置create_article.js
(在示例中,我正在傳遞您創建的數據庫用戶)
db = db.getSiblingDB("user");
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 }
});
掛載data
目錄
docker run --rm -it --name some-mongo -v /home/data/:/docker-entrypoint-initdb.d/ -e MONGO_INITDB_DATABASE=user -e MONGO_INITDB_ROOT_USERNAME=root -e MONGO_INITDB_ROOT_PASSWORD=mypass mongo:4.0.10
創建容器后,您將能夠看到DB,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.