前言
本章将使用docker安装mongo,前提条件是已经安装完docker并会使用docker。
如果还没有安装docker,可以参考在CentOS7下安装Docker
如果还不会docker,但需要学习mongodb相关的知识,可以参考另一篇博客,那里详细讲述了如何在Linux上安装mongodb环境。
附上博客链接 博客传送门
安装mongo
在Docker Hub上查找镜像
拉取官方镜像
[root@e2ab0x9jme3furrd ~]# docker pull mongo
查看本地镜像
[root@e2ab0x9jme3furrd ~]# docker images
创建文件夹
[root@e2ab0x9jme3furrd ~]# mkdir -p /data/mongo/data
[root@e2ab0x9jme3furrd ~]# mkdir -p /data/mongo/conf
[root@e2ab0x9jme3furrd ~]# mkdir -p /data/mongo/backup
[root@e2ab0x9jme3furrd ~]# cd /data/mongo
[root@e2ab0x9jme3furrd mongo]# ll
total 0
drwxr-xr-x 2 root root 6 Nov 30 15:46 backup
drwxr-xr-x 2 root root 6 Nov 30 15:46 conf
drwxr-xr-x 2 root root 6 Nov 30 15:45 data
运行容器
[root@e2ab0x9jme3furrd mongo]# docker run -v /data/mongo/data:/data/db -v /data/mongo/backup:/data/backup -v /data/mongo/conf:/data/configdb --name mongod -p 27017:27017 -d mongo --auth
查看容器状态
[root@e2ab0x9jme3furrd mongo]# docker ps
创建一个新用户
执行完前面的步骤,我们已经可以进入容器,并且可以打开mongo的命令行窗口。但是这样存在一个问题,就好像一个人没穿衣服在大街上,是很不安全的。
所以我们在此步创建一个新用户,每次进入mongo的命令窗口时输入用户名密码登录,这样在一定程度是解决了安全性问题,防止某些居心叵测的人登录你的数据库删库跑路。
[root@e2ab0x9jme3furrd mongo]# docker exec -it mongod mongo admin
MongoDB shell version v5.0.4
connecting to: mongodb://127.0.0.1:27017/admin?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("e303c2e5-ff96-4f50-bddc-6e676edeff45") }
MongoDB server version: 5.0.4
================
Warning: the "mongo" shell has been superseded by "mongosh",
which delivers improved usability and compatibility.The "mongo" shell has been deprecated and will be removed in
an upcoming release.
For installation instructions, see
https://docs.mongodb.com/mongodb-shell/install/
================
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
https://docs.mongodb.com/
Questions? Try the MongoDB Developer Community Forums
https://community.mongodb.com
> db.createUser({user: 'admin', pwd: '123456', roles: [ {role: 'userAdminAnyDa'} ]}) db.createUser({user: 'admin', pwd: '123456', roles: [ {role: 'userAdminAnyDat'} ]})db.createUser({user: 'admin', pwd: '123456', roles: [ {role: 'userAdminAnyData'} ]}db.createUser({user: 'admin', pwd: '123456', roles: [ {role: 'userAdminAnyDat'} ]})db.createUser({user: 'admin', pwd: '123456', roles: [ {role: 'userAdminAnyDa'} ]}) '} ]})
uncaught exception: SyntaxError: '' literal not terminated before end of script :
@(shell):1:6
> db.createUser({ user:'admin',pwd:'123456',roles:[ { role:'userAdminAnyDatabase', db: 'admin'},"readWriteAnyDatabase"]});
Successfully added user: {
"user" : "admin",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
},
"readWriteAnyDatabase"
]
}
> db.auth('admin', '123456')
1
> show dbs;
admin 0.000GB
config 0.000GB
local 0.000GB
测试连接
至此,我们就在Linux下安装好了mongo环境!!!