如何通过docker为mongodb创建新数据库和所需用户

时间:2018-05-14 11:43:26

标签: mongodb docker docker-compose

您好我正在使用docker文件下面创建一个mongodb实例,

version: '3.1'
services:
  mongo:
    image: mongo
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: XXXXXXXXXXX
    ports:
      - 27017:27017

现在我如何运行一些write + run init脚本来执行以下任务,

  • 创建数据库名称“data”
  • 在此数据库中创建集合
  • 为此数据库创建2个用户。

1 个答案:

答案 0 :(得分:1)

官方docker mongo映像支持数据库创建/初始化:

https://hub.docker.com/_/mongo/ 向下滚动到“MONGO_INITDB_DATABASE”

MONGO_INITDB_DATABASE
This variable allows you to specify the name of a database to be used 
for creation scripts in /docker-entrypoint-initdb.d/*.js (see 
Initializing a fresh instance below). MongoDB is fundamentally designed 
for "create on first use", so if you do not insert data with your 
JavaScript files, then no database is created.

Initializing a fresh instance
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 the 
MONGO_INITDB_DATABASE variable, if it is present, or test otherwise. 
You may also switch databases within the .js script.