Mongo authentication inside Docker

If you create the mongodb container (docker-compose up will build/pull the image and start a container) giving it the username and password, mongodb will configure itself on the first run and never again! Until you create a new container for that service, the default user/pass will be the ones set initially. If you want to change the default, a new container must be created. You can also add users after the container has started.

Only stopping the service containers (docker-compose stop) will not destroy de container. To do so, call docker-compose down or, when starting, call docker-compose up --force-recreate.

Regards


What worked for me was just adding the environment variable for the mongodb server.

ME_CONFIG_MONGODB_SERVER: mongo

like this:

version: '3.1'

services:

  mongo:
    image: mongo
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example

  mongo-express:
    image: mongo-express
    restart: always
    ports:
      - 8081:8081
    environment:
      ME_CONFIG_MONGODB_ADMINUSERNAME: root
      ME_CONFIG_MONGODB_ADMINPASSWORD: example
      ME_CONFIG_MONGODB_SERVER: mongo

In my case I had to first stop all my containers.

Then docker system prune -a --volumes

⚠️ This is the last resort. Before using this command check the docker doc,


Your docker-compose command:

docker-compose up --build --force-recreate    

Mongo image uses anonymous volumes, so you need also --renew-anon-volumes (doc):

docker-compose up --build --force-recreate --renew-anon-volumes

Otherwise previous volume with already initialized DB is used => INITDB env variables won't be used.