How to enable authentication on MongoDB through Docker?

后端 未结 10 2144
没有蜡笔的小新
没有蜡笔的小新 2020-11-29 18:53

I want to spin-up a docker for mongodb:latest but allow only certain user(s) to access certain db(s) (i.e. enable --auth). No one else should acces

10条回答
  •  囚心锁ツ
    2020-11-29 19:13

    Better solutions for furthering:
    https://blog.madisonhub.org/setting-up-a-mongodb-server-with-auth-on-docker/ https://docs.mongodb.com/v2.6/tutorial/add-user-administrator/

    Here's what I did for the same problem, and it worked.

    1. Run the mongo docker instance on your server

      docker run -d -p 27017:27017 -v ~/dataMongo:/data/db mongo
      
    2. Open bash on the running docker instance.

      docker ps
      

      CONTAINER IDIMAGE COMMAND CREATED STATUS PORTS NAMES

      b07599e429fb mongo "docker-entrypoint..." 35 minutes ago Up 35 minutes 0.0.0.0:27017->27017/tcp musing_stallman

      docker exec -it b07599e429fb bash
      root@b07599e429fb:/#
      

      Reference- https://github.com/arunoda/meteor-up-legacy/wiki/Accessing-the-running-Mongodb-docker-container-from-command-line-on-EC2

    3. Enter the mongo shell by typing mongo.

      root@b07599e429fb:/# mongo
      
    4. For this example, I will set up a user named ian and give that user read & write access to the cool_db database.

      > use cool_db
      
      > db.createUser({
          user: 'ian',
          pwd: 'secretPassword',
          roles: [{ role: 'readWrite', db:'cool_db'}]
      })
      

      Reference: https://ianlondon.github.io/blog/mongodb-auth/ (First point only)

    5. Exit from mongod shell and bash.

    6. Stop the docker instance using the below command.

      docker stop mongo
      
    7. Now run the mongo docker with auth enabled.

      docker run -d -p 27017:27017 -v ~/dataMongo:/data/db mongo mongod --auth
      

      Reference: How to enable authentication on MongoDB through Docker? (Usman Ismail's answer to this question)

    8. I was able to connect to the instance running on a Google Cloud server from my local windows laptop using the below command.

      mongo :27017/cool_db -u ian -p secretPassword
      

      Reference: how can I connect to a remote mongo server from Mac OS terminal

提交回复
热议问题