I'm running a dockerized mongo container.
I'd like to create a mongo image with some initialized data.
Any ideas?
Docker is great for running databases in a development environment! You can even use it for databases of small, non-critical projects which run on a single server.
A more self-contained approach:
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:
This approach is especially well suited to:
How to:
Create a Dockerfile for your derived image that copies your init scripts
FROM mongo:3.4 COPY seed-data.js /docker-entrypoint-initdb.d/
Build your docker image
docker build -t mongo-sample-data:3.4 .
Optionally, push your image to a docker registry for others to use
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With