mongodbdockerconnection-string

Default user and password for MongoDB docker


I am running a local MongoDB docker using following command

docker run --name mongodb -p 27017:27017 -d mongodb/mongodb-community-server:latest

This works fine and I can connect to this using following connection string "mongodb://localhost:27017/"

But in my Java code I want to connect using username and password (to keep it consistent with cloud based connection string) something like

mongodb://admin:password@localhost:27017/

But this doesn't work. What user and password will works with docker image? or is there a way I can pass user and password at DB startup?

I tried following but docker doesn't start with this.

docker run --name mongodb -p 27017:27017 -d mongodb/mongodb-community-server:latest -e MONGO_INITDB_ROOT_USERNAME=admin -e MONGO_INITDB_ROOT_PASSWORD=password

Any hints to resolve this will be helpgul

Thaks


Solution

  • docker run --name mongodb -p 27017:27017 -d \
        -e MONGO_INITDB_ROOT_USERNAME=admin \
        -e MONGO_INITDB_ROOT_PASSWORD=password \
        mongo:latest
    

    Use official OpenSource version of MongoDB image, which does support passing the username and password environment variables. This works with

    mongodb://admin:password@localhost:27017/