网上有不少教程,但照做起来却总是不太顺利,因此,自己做好后写一个
[root@k8s_mongodb /]# mkdir -p /data/mongo/ && cd /data/mongo/
[root@k8s_mongodb /]# mkdir -p db/db_a/{data,log}
[root@k8s_mongodb /]# cat << EOF | tee docker-compose.yaml
version: '3.1'
services:
mongo:
image: mongo:4.2
ports:
- 27017:27017
restart: always
tty: true
environment:
MONGO_INITDB_ROOT_USERNAME: Admin
MONGO_INITDB_ROOT_PASSWORD: Admin123Abc123
volumes:
- /etc/localtime:/etc/localtime:ro
- ./db/db_a/data:/data/db
- ./db/db_a/log:/data/log
command:
- /bin/bash
- -c
- mongod --port 27017 --bind_ip_all --auth --dbpath "/data/db" --logpath "/data/log/db.log"
# 这个地方很有意思,如果写成"command: mongod ....."形式,则mongodb这个容器会不断的重启,并且未提示一些文件不存在之类的错误信息,原因未知
mongo-express:
links:
- mongo
image: mongo-express
restart: always
ports:
- 8081:8081
environment:
ME_CONFIG_OPTIONS_EDITORTHEME: 3024-night
ME_CONFIG_BASICAUTH_USERNAME: mongoexpress
ME_CONFIG_BASICAUTH_PASSWORD: mongoexpress
ME_CONFIG_MONGODB_ADMINUSERNAME: Admin
ME_CONFIG_MONGODB_ADMINPASSWORD: Admin123Abc123
EOF
[root@k8s_mongodb mongo]# docker ps # 查看docker是否正常启动
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
74cc67cc3a09 mongo-express "tini -- /docker-ent…" 9 minutes ago Up 9 minutes 0.0.0.0:8081->8081/tcp mongo_mongo-express_1
2c43929ecbda mongo:4.2 "docker-entrypoint.s…" 9 minutes ago Up 9 minutes 0.0.0.0:27017->27017/tcp mongo_mongo_1
# 初始化一下
[root@k8s_mongodb mongo]# docker exec -it mongo_mongo_1 bash
root@2c43929ecbda:/# sed -i 's\bind\#bind\' /etc/mongod.conf.orig # 开始远程链接,这步可以不做
root@2c43929ecbda:/# mongo
> use adminuse admin
switched to db admin
>db.createUser({
user: "Admin",
pwd: "Admin123Abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
})
......Successfully added user: ...... # 添加用户成功!
> db.auth('Admin','Admin123Abc123')
1 # 认证通过!
# 再添加一个
>db.createUser({
user: "mongoexpress",
pwd: "mongoexpress",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
})
>db.auth('mongoexpress','mongoexpress')
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
从浏览器访问mongoexpress验证一下:http://你的ip:8081/ 帐号: mongoexpress/mongoexpress
16.png
网友评论