0

I have a docker container that is running a mongo database, and then a service that is checking for data stored on it, but first some basic setup has to be done like adding a user and collection. I have a script that does all of that, but as of now I have to run it manually with docker exec -it logging-service_mongo_1 bash docker-entrypoint-initdb.d/test2.sh Note that the script is a volume for the container. Is there a way that I can have the script run when the container running mongo has been established? I have tried using entrypoint, but had no luck with that. Apologies if this information is lacking, this is my first attempt using both docker and mongodb

One more thing is that the code I inherited contains this

CMD [ "npm", "run", "start:prod" ] 

which I think may have been messing with the entrypoint when I attempted that

0

2 Answers 2

2

If you are using the official MongoDB docker image, take a look at the "Initializing a fresh instance" section of the image documentation:

When a container is started for the first time it will execute files with extensions .sh and .js that are found in /docker-entrypoint-initdb.d. Files will be executed in alphabetical order. .js files will be executed by mongo using the database specified by the MONGO_INITDB_DATABASE variable, if it is present, or test otherwise. You may also switch databases within the .js script.

You can either build a new image based on this one that bakes the script into /docker-entrypoint-initdb.d, or you can mount scripts into that directory using bind mounts (docker run -v $PWD/myscript.sh:/docker-entrypoint-initdb.d/myscript.sh ...)

Sign up to request clarification or add additional context in comments.

Comments

0

if you only need to setup the user and password yo can set it while starting the container

docker run -d --name container_name \ -e MONGO_INITDB_ROOT_USERNAME=admin \ -e MONGO_INITDB_ROOT_PASSWORD=password \ mongo 

If you use docker-compose

 mongodb: container_name: mongodb ports: - 27017:27017 environment: MONGO_INITDB_ROOT_USERNAME: admin MONGO_INITDB_ROOT_PASSWORD: password volumes: - mongo_data:/data/db 

Regarding the collection it will be created once you insert data on it.

If you really need to do this after the mongo container start, i suggest you to create another container that tries to setup the mongo when it detects that mongo turned on

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.