Docker Mongo add user name and password


Docker compose file

version: "2"
    image:  mongo:3.2.4
    container_name: mongo
    #command: mongod --auth
    mem_limit: 1g
    restart: always
     - "37017:27017/tcp"
     - /etc/localtime:/etc/localtime
     - $PWD/data/db:/data/db

Mongo does not enable authentication permission to start

  1. Check docker compose If the YML file has the line command: mongod — auth, comment it out; If not or noted, go to step 2)
  2. Restart Mongo
    docker-compose up -d mongo

Add users (users need to be added for each database)

  1. Enter the docker container of Mongo, and the command is:
    docker exec -it mongo bash
  2. Enter Mongo, command:

First, create a root user in the admin database

use admin

Add the same user for each other database

You need to create as many users as there are databases, because once permission verification is enabled, the link cannot be verified without creating a user’s database
Query all database names of Mongo
show dbs

use other_db
Each database can create different user names and passwords. However, in order to facilitate unified management, they are generally created as the same. For security reasons, different user passwords can be created. Role represents the permissions of the current user in this database

Output after successful creation

The database can be created freely before verification is enabled. Generally, if the specified database does not exist, it will be created automatically
After the verification is enabled, the database needs to be created manually, and then the code links the specified database and account password for data operation
db.createUser({user: "AUser",pwd: "123456",roles: [{role: "readWrite",db: "account"}]})
Create account database, user: auser, password: 123456
use account
Insert any data

> show dbs
account  0.000GB
admin    0.000GB
local    0.000GB

Then you can link the account database through authorization verification in the code

Delete database
Enter the database to be deleted and execute the delete command
use account

After the creation is completed, execute the following command to check whether the creation is successful

use admin
Normally, the result of creating user information should be returned

If an incorrect user is added, it can be removed by the following command

Or delete the user under the specified database
use account

Start permission restart Mongo

Modify docker compose YML file, remove the comment of command: mongod — auth just now

Restart Mongo

docker-compose up -d

After startup, log in to docker and check

docker exec -it mongo bash
use account
A return of 1 indicates success