Is database not initialized when spinning up a MongoDB docker container?

Hi, I am trying to initialize a database when starting a MongoDB docker container, powered by docker-compose.

Here is my docker-compose.yml :

version: '3.8'

    image: mongo:5.0.6
    restart: always
      TZ: "Europe/London"
      - 27018:27017

I successfully connected to the MongoDB container but it did not give me the database named ferndb which I wanted to initialize :

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB

Any help is appreciated much.

Hi @marc and welcome in the MongoDB Community :muscle: !

I think this variable is just used to defined the default DB that the JS scripts in /docker-entrypoint-initdb.d/*.js default to if you insert some data or init something (indexes, create timeseries collections, …). It’s like the default use myDB that you can use.

If you don’t create anything in that DB (I don’t see any script in here) then nothing happens and the DB isn’t created. MongoDB will create it if you actually store something in there. Else there is no reason to create an empty vessel.

I’d add that you should try to config this so it’s actually a Replica Set and not just a standalone node which isn’t recommend for a prod env but I don’t know what you are doing ;-). At least having a RS enable a bunch of features (ACID transactions, Change Streams, …).

Personally I use this to hack around on a daily basis:

alias mdb='docker run --rm -d -p 27017:27017 -h $(hostname) --name mongo mongo:5.0.6 --replSet=test && sleep 4 && docker exec mongo mongo --eval "rs.initiate();"'

And then I use alias msh='docker exec -it mongo mongosh --quiet' to connect.

This gives me a single node RS which is enough for me to answer community questions or I can switch to a cluster in Atlas if I need something special (sharding, etc).


PS: see Docker => MONGO_INITDB_DATABASE section.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.