简体   繁体   中英

Mongodb docker container with client access control

I want to create a docker container with a mongodb configured with client access control (user authentication, see this ).

I have successfully configured a docker container with mongo using this image . But it doesn't use mongo access control.

The problem is that to enable access control I have to run mongodb with a specific command line ( --auth ) but only after creating the first admin user.

With a standard mongodb installation I normally perform these steps:

  • run mongod without --auth
  • connect to mongo and add the admin user
  • restart mongo with --auth

How I'm supposed to do it with docker? Because mongo image always start without --auth . Should I create a new image? Or maybe modify the entry point?

Probably I'm missing something, I'm new to docker...

Ok, I have found a solution. Basically MongoDb has a feature that allow to setup access security ( --auth ) but permit localhost connection. See mongo local exception .

So this is my final script:

# Create a container from the mongo image, 
#  run is as a daemon (-d), expose the port 27017 (-p),
#  set it to auto start (--restart)
#  and with mongo authentication (--auth)
# Image used is https://hub.docker.com/_/mongo/
docker pull mongo
docker run --name YOURCONTAINERNAME --restart=always -d -p 27017:27017 mongo mongod --auth

# Using the mongo "localhost exception" add a root user

# bash into the container
sudo docker exec -i -t YOURCONTAINERNAME bash

# connect to local mongo
mongo

# create the first admin user
use admin
db.createUser({user:"foouser",pwd:"foopwd",roles:[{role:"root",db:"admin"}]})

# exit the mongo shell
exit
# exit the container
exit

# now you can connect with the admin user (from any mongo client >=3 )
#  remember to use --authenticationDatabase "admin"
mongo -u "foouser" -p "foopwd" YOURHOSTIP --authenticationDatabase "admin"

In case you are able to use other existing images, there is a well maintained image with default authentication enabled for MongoDB and easy to plug in, called tutum-docker-mongodb .

It also uses environmental variables which you can use in you app.

I included it in my tutum.yml (or docker-compose.yml ) like so:

mongo:
  image: 'tutum/mongodb:latest'
  environment:
    - MONGODB_PASS=<your-password-here>
  ports:
    - '27017:27017'
    - '28017:28017'

Finally I linked the web service using:

web:
  image: 'my-image'
  links:
    - 'mongo:mongo'
  ports:
    - '80:3000'
  restart: always

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM