使用docker-compose构建mongodb服务并导入基础数据示例。
1、文件目录结构
——mongo/
|——docker-compose.yml
|——mongo-Dockerfile
|——setup.sh
|——data/
|——xxx1.json
|——xxx2.json
2、docker-compose.yml
services:
mongo_db:
build:
context: .
dockerfile: mongo-Dockerfile
restart: always
ports:
- "27019:27017"
volumes:
- "/home/volumes/mongo:/data/db"
- "/etc/localtime:/etc/localtime"
3、mongo-Dockerfile
FROM mongo:3.4
ENV WORKSPACE /usr/local/work
ENV AUTO_RUN_DIR /docker-entrypoint-initdb.d
ENV INSTALL_MONGO_SHELL setup.sh
RUN mkdir -p $WORKSPACE
COPY ./data/*.json $WORKSPACE/
COPY ./$INSTALL_MONGO_SHELL $AUTO_RUN_DIR/
RUN chmod a+x $AUTO_RUN_DIR/$INSTALL_MONGO_SHELL
4、setup.sh
#!/bin/bash
mongo <<EOF
use admin;
db.createUser({ user: 'root', pwd: '123456', roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] }); use new_db;
db.createCollection("collection1");
db.createCollection("collection2");
EOF mongoimport --db new_db --collection collection1 --file $WORKSPACE/xxx1.json
mongoimport --db new_db --collection collection2 --file $WORKSPACE/xxx2.json
5、在docker-compose.yml目录下执行
docker-compose up -d
over。