mongodb - 如何通过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 脚本来执行以下任务,
- 创建数据库名称“数据”
- 在此数据库中创建集合
- 为此数据库创建 2 个用户。
解决方案
官方 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.
推荐阅读
- c# - 如何将字符串转换为对象的定义
- reactjs - 如何将现有的 Strapi 服务器(没有管理员访问权限)与 React 连接?
- go - QOR 示例恐慌
- android - Android在录制视频时禁用Camera2自动对焦
- java - AtomicLong.set vs LongAccumulator.accumulate 性能 java?
- mysql - 将同一列与总和相加,以及根据不同条件对同一列进行部分总和
- javascript - 如何调试运行时 TypeError
- php - laravel @include 不适用于部分('脚本')
- javascript - 除非查询为空,否则 Mongoose-fuzzy-searching 返回空数组
- swift - 我应该在哪个线程上收听自定义框架中的位置变化?