首页 > 解决方案 > 如何通过docker为mongodb创建新数据库和所需用户

问题描述

嗨,我正在使用下面的 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 脚本来执行以下任务,

标签: mongodbdockerdocker-compose

解决方案


官方 docker mongo 镜像支持 db 创建/初始化:

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.

推荐阅读