mongo docker image not running script after created

Viewed 1542

I'm using docker-compose to create 3 diferent containers for a frontend, backend and mongo instance. the 3 of them are running and connected between them, but I need to create an admin user on DB as soon as the mongo instance is running. According to mongo image documentation every script located on docker-entrypoint-initdb.d should be run after the instance is created. As I already said I'm using docker compose so theres no Dockerfile for mongo, just a service using the official mongo image so I've set a volume to this file [don't know if because of that the script is not running, because is a symlink instead of a copied file]. So I tried to run a command to run this script but it doesn't work, but if then I do a docker exec to the mongodb instance and run the script by myself it will work and create the admin user.

So, how can i make this script run after the instance is created?

this is my docker-compose.yml file

mongodb:
    container_name: mongodb
    image: mongo
    command: /bin/bash "cd /docker-entrypoint-initdb.d && mongo-init.sh"
    networks:
      - backend-network
    volumes:
      - './db:/data/db'
      - './mongo-init.sh:/docker-entrypoint-initdb.d/mongo-init.sh'
    tty: true
    restart: always
1 Answers

You don't need to modify the mongo command because it will cause issues to the mongodb container. By defining command you will override the original CMD which expected to run. the script will be executed automatically as long as you have mounted it under /docker-entrypoint-initdb.d/ as explained in here

Note that scripts will be executed only one time at the start of your container and in order to make it execute again you need to delete the /data/db volume which is associated with your container

Related