MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Come abilitare l'autenticazione su MongoDB tramite Docker?

Se dai un'occhiata a:

  • https://github.com/docker-library/mongo/blob/master/4.2/Dockerfile
  • https://github.com/docker-library/mongo/blob/master/4.2/docker-entrypoint.sh#L303-L313

noterai che ci sono due variabili usate in docker-entrypoint.sh :

  • MONGO_INITDB_ROOT_USERNAME
  • MONGO_INITDB_ROOT_PASSWORD

Puoi usarli per configurare l'utente root. Ad esempio, puoi utilizzare il seguente docker-compose.yml file:

mongo-container:
  image: mongo:3.4.2
  environment:
      # provide your credentials here
      - MONGO_INITDB_ROOT_USERNAME=root
      - MONGO_INITDB_ROOT_PASSWORD=rootPassXXX
  ports:
    - "27017:27017"
  volumes:
      # if you wish to setup additional user accounts specific per DB or with different roles you can use following entry point
    - "$PWD/mongo-entrypoint/:/docker-entrypoint-initdb.d/"
  # no --auth is needed here as presence of username and password add this option automatically
  command: mongod

Ora, quando avvii il contenitore con docker-compose up dovresti notare le seguenti voci:

...
I CONTROL  [initandlisten] options: { net: { bindIp: "127.0.0.1" }, processManagement: { fork: true }, security: { authorization: "enabled" }, systemLog: { destination: "file", path: "/proc/1/fd/1" } }
...
I ACCESS   [conn1] note: no users configured in admin.system.users, allowing localhost access
...
Successfully added user: {
    "user" : "root",
    "roles" : [
        {
            "role" : "root",
            "db" : "admin"
        }
    ]
}

Per aggiungere utenti personalizzati oltre a root, usa lo script eseguibile entrypoint (posto in $PWD/mongo-entrypoint dir poiché è montato in docker-compose al punto di ingresso):

#!/usr/bin/env bash
echo "Creating mongo users..."
mongo admin --host localhost -u USER_PREVIOUSLY_DEFINED -p PASS_YOU_PREVIOUSLY_DEFINED --eval "db.createUser({user: 'ANOTHER_USER', pwd: 'PASS', roles: [{role: 'readWrite', db: 'xxx'}]}); db.createUser({user: 'admin', pwd: 'PASS', roles: [{role: 'userAdminAnyDatabase', db: 'admin'}]});"
echo "Mongo users created."

Verrà eseguito lo script Entrypoint e verranno creati utenti aggiuntivi.