Docker
在 Docker 中為 MongoDB 創建一個新使用者
我正在使用預設的 MongoDB Docker 映像,並且正在嘗試為數據庫創建一個新使用者。
我目前正在嘗試這樣做:
FROM docker.io/mongo:3.2 MAINTAINER <alexandernst> alexandernst@gmail.com ADD create_ddbb.js /tmp/ RUN mongod --fork --logpath /var/log/mongodb.log \ && sleep 5 && mongo foobar /tmp/create_ddbb.js
和
create_ddbb.js
:db.createUser( { user: "*******", pwd: "*******************", roles: [ { role: "readWrite", db: "foobar" } ] } );
當我建構 Dockerfile 時,我看到:
Step 4 : RUN mongod --fork --logpath /var/log/mongodb.log && sleep 5 && mongo foobar /tmp/create_ddbb.js ---> Running in 58ba44d02508 about to fork child process, waiting until server is ready for connections. forked process: 9 child process started successfully, parent exiting MongoDB shell version: 3.2.6 connecting to: foobar Successfully added user: { "user" : "***********", "roles" : [ { "role" : "readWrite", "db" : "foobar" } ] } ---> e73b6c8c8b83 Removing intermediate container 58ba44d02508 Successfully built e73b6c8c8b83
所以創建了使用者,但是當我嘗試連接時,我得到:
mongo_1 | 2016-05-13T17:44:02.159+0000 I NETWORK [initandlisten] connection accepted from 172.20.0.4:41294 #1 (1 connection now open) mongo_1 | 2016-05-13T17:44:02.160+0000 I ACCESS [conn1] SCRAM-SHA-1 authentication failed for ********* on foobar from client 172.20.0.4 ; UserNotFound: Could not find user *********@foobar mongo_1 | 2016-05-13T17:44:02.160+0000 I NETWORK [conn1] end connection 172.20.0.4:41294 (0 connections now open)
為什麼會這樣?如何持久化創建的使用者?
我的解決方案:
在你的內部
Dockerfile
:ADD create_ddbb.js /tmp/ RUN mongod -f /etc/mongod.conf --fork --logpath /var/log/mongodb.log \ && sleep 5 \ && mongo <YOUR DATABASE> /tmp/create_ddbb.js
裡面
create_ddbb.js
:db.createUser( { user: "your_user", pwd: "********************", roles: [ { role: "dbOwner", db: "your_database" } ] } , { w: "majority", wtimeout: 5000 } ); db.createCollection("test");
最後
createColleciton("test")
是非常重要的。沒有它,createUser
則不會應用。我不知道具體為什麼,對不起。