Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

mongodb - Initialize data on dockerized mongo

I'm running a dockerized mongo container.

I'd like to create a mongo image with some initialized data.

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A more self-contained approach:

  • create javascript files that initialize your database
  • create a derived MongoDB docker image that contains these files

There are many answers that use disposable containers or create volumes and link them, but this seems overly complicated. If you take a look at the mongo docker image's docker-entrypoint.sh, you see that line 206 executes /docker-entrypoint-initdb.d/*.js files on initialization using a syntax: mongo <db> <js-file>. If you create a derived MongoDB docker image that contains your seed data, you can:

  • have a single docker run command that stands up a mongo with seed data
  • have data is persisted through container stops and starts
  • reset that data with docker stop, rm, and run commands
  • easily deploy with runtime schedulers like k8s, mesos, swarm, rancher

This approach is especially well suited to:

  • POCs that just need some realistic data for display
  • CI/CD pipelines that need consistent data for black box testing
  • example deployments for product demos (sales engineers, product owners)

How to:

  1. Create and test your initialization scripts (grooming data as appropriate)
  2. Create a Dockerfile for your derived image that copies your init scripts

    FROM mongo:3.4
    COPY seed-data.js /docker-entrypoint-initdb.d/
    
  3. Build your docker image

    docker build -t mongo-sample-data:3.4 .
    
  4. Optionally, push your image to a docker registry for others to use

  5. Run your docker image

    docker run                               
        --name mongo-sample-data             
        -p 27017:27017                       
        --restart=always                     
        -e MONGO_INITDB_DATABASE=application 
        -d mongo-sample-data:3.4
    

By default, docker-entrypoint.sh will apply your scripts to the test db; the above run command env var MONGO_INITDB_DATABASE=application will apply these scripts to the application db instead. Alternatively, you could create and switch to different dbs in the js file.

I have a github repo that does just this - here are the relevant files.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...