下载文件
cd /home/mongodb wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel70-4.2.16-rc0.tgz
安装服务
yum -y install net-snmp cd /home/mongodb tar -zxvf mongodb-linux-x86_64-rhel70-4.2.16-rc0.tgz mv mongodb-linux-x86_64-rhel70-4.2.16-rc0 mongodb mv mongodb /usr/local/
创建配置文件
vim /etc/mongodb.conf port=27017
#数据目录dbpath = /usr/local/mongodb/data/db #日志文件logpath = /usr/local/mongodb/logs/mongoLogs.log #设置后台运行fork =true#日志输出方式logappend =true#启用日志文件,默认启用journal=true##这个选项可以过滤掉一些无用的日志信息,若需要调试使用请设置为falsequiet=true##允许远程访问bind_ip=0.0.0.0 ##开启认证,必选先添加用户,先不开启(不用验证账号密码)auth=true
mkdir-p /usr/local/mongodb/data/db mkdir-p /usr/local/mongodb/logs/
创建启动脚本(配置开机自启动)
##chkconfig: 2345 80 90#description: mongodbstart() { /usr/local/mongodb/bin/mongod -f /etc/mongodb.conf } stop() { /usr/local/mongodb/bin/mongod -f /etc/mongodb.conf --shutdown} case "$1"instart) start;; stop) stop;; restart) stopstart;; *) echo$"Usage: $0 {start|stop|restart}"exit1esac
运行命令启用脚本
chmod +x /etc/rc.d/init.d/mongod chkconfig --add mongod chkconfig --level 345 mongod on chkconfig --list mongod service mongod start |
配置环境变量(注意若直接修改/etc/profile 这种方式不起作用)
cd /etc/profile.d vi mongo.sh
#!/bin/bash MONGO_HOME=/usr/local/mongodb/bin PATH=$MONGO_HOME/bin:$PATH export PATH sh mongo.sh source /etc/profile
进入客户端创建用户
mongo $mongo #进入mongo控制台 MongoDB shell version v3.4.10 connecting to: mongodb://127.0.0.1:27017 MongoDB server version: 3.4.10 > > use admin #进入admin库 switched to db admin > db #查看当前数据库 admin > db.createUser({user:"master",pwd:"123456",roles:[{"role":"userAdminAnyDatabase","db":"admin"}]}) #创建超级用户 Successfully added user: { "user" : "master", "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ] }
打开mongodb的验证
net: port: 27017 bindIp : 0.0.0.0 #监听所有ip security: authorization: enabled #开启密码验证 用超级用户登录mongo $mongo MongoDB shell version v3.4.10 connecting to: mongodb://127.0.0.1:27017 MongoDB server version: 3.4.10 > >use admin switched to db admin >db.auth("master","123456") #用超级用户登录了 去创建一个test库,然后创建test库的账户密码 $mongo MongoDB shell version v3.4.10 connecting to: mongodb://127.0.0.1:27017 MongoDB server version: 3.4.10 > >use admin switched to db admin >db.auth("master","123456") #用超级用户登录了 >use test switched to db test > db.createUser({user: "test",pwd: "test",roles: [{ role: "readWrite", db: "test" }] }) #创建对test库有读写权限的账户密码 Successfully added user: { "user" : "test", "roles" : [ { "role" : "readWrite", "db" : "timecash" } ] }
测试test库的账户密码是否能登录
$ mongo MongoDB shell version v3.4.10 connecting to: mongodb://127.0.0.1:27017 MongoDB server version: 3.4.10 > >use test switched to db test >db.auth("test","test") 1 >db.abc.insert({"a":1,"b":2}) #在test库的abc表插入数据 用test账户直接登录 $ mongo test -u test -p test MongoDB shell version v3.4.10 connecting to: mongodb://127.0.0.1:27017/timecash MongoDB server version: 3.4.10 > db test 建用户语句 db.createUser({user:"root", pwd:"123456", roles: [{role:"dbOwner", db: "test"}]})