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

前端 未结 3 2064
春和景丽
春和景丽 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:10

    The problem was that information could not be saved on /db/data, so I've created a solution creating my own data directory.

    # Parent Dockerfile https://github.com/docker-library/mongo/blob/982328582c74dd2f0a9c8c77b84006f291f974c3/3.0/Dockerfile
    FROM mongo:latest
    
    # Modify child mongo to use /data/db2 as dbpath (because /data/db wont persist the build)
    RUN mkdir -p /data/db2 \
        && echo "dbpath = /data/db2" > /etc/mongodb.conf \
        && chown -R mongodb:mongodb /data/db2
    
    COPY . /data/db2
    
    RUN mongod --fork --logpath /var/log/mongodb.log --dbpath /data/db2 --smallfiles \
        && CREATE_FILES=/data/db2/scripts/*-create.js \
        && for f in $CREATE_FILES; do mongo 127.0.0.1:27017 $f; done \
        && INSERT_FILES=/data/db2/scripts/*-insert.js \
        && for f in $INSERT_FILES; do mongo 127.0.0.1:27017 $f; done \
        && mongod --dbpath /data/db2 --shutdown \
        && chown -R mongodb /data/db2
    
    # Make the new dir a VOLUME to persists it 
    VOLUME /data/db2
    
    CMD ["mongod", "--config", "/etc/mongodb.conf", "--smallfiles"]
    

    Thanks to @yosifkit from the docker-library/mongo Github project for pointing that the volume would store the data in the resulting image. I missed that on the documentation.

提交回复
热议问题