Reputation: 11
Really simple Dockerfile:
FROM mongo:3.2.10
#create DB directory
RUN mkdir -p /data/db
EXPOSE 27017
CMD ["mongod"]
When I run the container I want to automatically create a DB called "CBDB"
. I do not want to manually run the mongo shell, want the new DB to be created automatically.
Thanks!
Upvotes: 1
Views: 2144
Reputation: 515
You can execute mongo as a daemon and write an script to be executed in an entrypoint.
https://docs.mongodb.com/manual/tutorial/write-scripts-for-the-mongo-shell/
As a simple example, use this Dockerfile and entrypoint:
FROM mongo:3.2.10
#create DB directory
RUN mkdir -p /data/db
EXPOSE 27017
COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
ENTRYPOINT ["./entrypoint.sh"]
In the entrypoint, you can use the mongo as a daemon, and execute a one liner to create a database and a collection. Remember to use tail (or something like supervisord) to assure that the container does not gets stopped:
#!/bin/bash
mongod --fork --logpath /var/log/mongo.log
mongo --eval "db = db.getSiblingDB('new_db'); db.createCollection('new_collection');"
tail -f /var/log/mongo.log
Upvotes: 2