1

I am trying to find a way to create a docker container that when created has the db user profile created automatically. I am using a dockerfile and thought i could add the commands to create the user in it.

Anyone done this before and know what I am doing wrong here. I am no expert at Docker.

FROM mongo:latest

RUN mongo &&\
    use tewtdb &&\
    db.createUser({user: '<user>', pwd: '<pwrd>', roles[{role: 'dbOwner', db: 'tewtdb'}]})

EXPOSE 27017

CMD ["mongod"]

enter image description here

Mitchell Day
  • 196
  • 2
  • 14
  • Does this answer your question? [Initialize data on dockerized mongo](https://stackoverflow.com/questions/39348478/initialize-data-on-dockerized-mongo) – jabbson Dec 03 '21 at 00:49
  • Alternatively with seeding image: https://stackoverflow.com/questions/31210973/how-do-i-seed-a-mongo-database-using-docker-compose – jabbson Dec 03 '21 at 00:51
  • I ended up running the default mongo image, then ran another batch script which fed it the js file with the "use " and "db.createUser()". It was getting connection errors. But then i started waiting a short period before running the second batch and it worked. – Mitchell Day Dec 03 '21 at 01:42

1 Answers1

2

shell

docker run --name mongodb -d -e MONGO_INITDB_ROOT_USERNAME=user -e MONGO_INITDB_ROOT_PASSWORD=pwd -v D:/mdb:/data/db -p 27117:27017 mongo:5.0

dockerfile-compose

version: '3'
services:
  standalone:
    image: mongo:5.0
    ports:
      - 27117:27017
    environment:
      - MONGO_INITDB_ROOT_USERNAME=user
      - MONGO_INITDB_ROOT_PASSWORD=pwd
    volumes:
      - D:/mdb:/data/db
docker-compose -f docker-compose.yml up -d
YuTing
  • 6,555
  • 2
  • 6
  • 16
  • So I already have those environment user variables for mongo. But i wanted to create a separate user inside mongo that only has access to a selected database. To do this I docker run something similar to this, wait 10 seconds (in the script) then using those mongo credentials, log in using mongo
    and copy and run a js file with the new user details. Works a treat
    – Mitchell Day Mar 09 '22 at 00:35