Docker与mongo用户

时间:2016-05-17 13:43:57

标签: mongodb docker dockerfile

我出于安全原因尝试创建mongodb用户。现在我有以下Dockerfile:

FROM mongo:3.3

RUN mongo admin --eval "db.getSiblingDB('db').createUser({user: 'test', pwd: 'test'})"

当我运行docker时,我收到以下错误:

MongoDB shell version: 3.3.5
connecting to: admin
2016-05-17T13:31:07.821+0000 W NETWORK  [thread1] Failed to connect to 127.0.0.1:27017, reason: Connection refused
2016-05-17T13:31:07.821+0000 E QUERY    [thread1] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed :
connect@src/mongo/shell/mongo.js:229:14
@(connect):1:6

exception: connect failed
ERROR: Service 'mongodb' failed to build: The command '/bin/sh -c mongo admin --eval "db.getSiblingDB('db').createUser({user: 'test', pwd: 'test'})"' returned a non-zero code: 1

我认为这是因为此时mongod还没有运行?

那么如何创建这个mongodb用户呢?

1 个答案:

答案 0 :(得分:1)

Dockerfile:

FROM mongo:3.3
COPY setup.sh /setup.sh
RUN /setup.sh

setup.sh:

#!/bin/bash

mongod &

RET=1
while [[ RET -ne 0 ]]; do
    echo "=> Waiting for confirmation of MongoDB service startup"
    sleep 5
    mongo admin --eval "help" >/dev/null 2>&1
    RET=$?
done

ADMINUSER=user
ADMINPASS=pass

echo "=> Creating an admin user in MongoDB"
mongo admin --eval "db.createUser({user: '$ADMINUSER', pwd: '$ADMINPASS', roles:[{role:'root',db:'admin'}]});"

mongod --shutdown