Piu130
Piu130

Reputation: 1407

Docker with mongo user

I'm trying to create a mongodb user for security reason. Now I have the following Dockerfile:

FROM mongo:3.3

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

When I run docker I get the following error:

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

I think this is because mongod is not running at this moment?

So how can I create this mongodb user?

Upvotes: 0

Views: 1164

Answers (1)

Dmitry Efimenko
Dmitry Efimenko

Reputation: 11178

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

Upvotes: 1

Related Questions