How to create a Mongo Docker Image with default collections and data?

前端 未结 3 2059
春和景丽
春和景丽 2020-11-30 02:18

I need support here to build my own mongo docker image.

I have a list of scripts to create and insert data into the MongoDB that shall be called in my Dockerfile to

3条回答
  •  野性不改
    2020-11-30 03:05

    During a docker image build, each build command like RUN is launched in it's own docker container and then when the command completes the data is committed as an image. If you run dockviz images --tree while doing a build you will get the idea.

    In your case mongod has started and stopped long before you need it. You need to start mongo and run your scripts all in the one RUN step. You can achieve that by using a shell script that launches mongod and inserts your data.

    Your Dockerfile will run:

    RUN mongo_create_insert.sh
    

    Then mongo_create_insert.sh contains all your mongo dependent steps:

    #!/usr/bin/env bash
    
    mongod --fork --logpath /var/log/mongodb.log --dbpath /data/db/
    
    FILES=scripts/*-create.js
    for f in $FILES; do mongo mydb $f; done
    
    FILES=scripts/*-insert.js
    for f in $FILES; do mongo mydb $f; done
    
    mongod --shutdown
    

    As a side note, I tend to install Ansible in my base image and use that to provision Docker images in single RUN command rather than doing lots of shell RUN steps in a Dockerfile (which is just a glorified shell script in the end). You lose some of the build caching niceness but we've moved on from provisioning with shell scripts for a reason.

提交回复
热议问题