环境
CentOS Linux release 7.6.1810 (Core)
mongodb-linux-x86_64-4.0.17.tgz
下载页面
https://www.mongodb.com/download-center/community
下载地址
https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-4.0.17.tgz
1、下载并解压
cd /usr/local/soft/package
# 下载mongodb
wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-4.0.17.tgz
# 解压
tar -zxvf mongodb-linux-x86_64-4.0.17.tgz
mv mongodb-linux-x86_64-4.0.17 /usr/local/soft
# 建立软连接
ln -s /usr/local/soft/mongodb-linux-x86_64-4.0.17 /usr/local/soft/mongodb
2、新建配置文件
# 创建数据存放目录
mkdir -p /usr/local/soft/mongodb/data/mongodb
# 创建日志存放目录
mkdir -p /usr/local/soft/mongodb/log
# 创建配置文件存放目录
mkdir -p /usr/local/soft/mongodb/conf
# 新建配置文件
vim /usr/local/soft/mongodb/conf/mongod.conf
systemLog:
destination: file
path: "/usr/local/soft/mongodb/log/mongod.log"
logAppend: true
storage:
dbPath: "/usr/local/soft/mongodb/data/mongodb"
journal:
enabled: true
processManagement:
fork: true
net:
bindIp: 0.0.0.0
port: 27017
#security:
# authorization: enabled
3、启动mongodb
cd /usr/local/soft/mongodb/bin
# 方式一 命令行加参数
./mongod --port 27017 --dbpath=/usr/local/soft/mongodb/data/mongodb --bind_ip=0.0.0.0
# 方式二 使用配置文件(推荐)
./mongod -f ../conf/mongod.conf
# 或者
# ./mongod --config ../conf/mongod.conf
4、查看MongoDB是否启动
netstat -lanp | grep "27017"
5、登录MongoDB
./mongo
use admin
6、防火墙添加27017端口
# 查看防火墙列表
firewall-cmd --list-all
# 添加27017端口(–permanent永久生效,没有此参数重启后失效)
firewall-cmd --permanent --add-port=27017/tcp
# 更新防火墙规则
firewall-cmd --reload
7、关闭mongodb
ps -ef | grep mongo
kill -2 xxxx
8、根据警告信息进行优化
** WARNING: Access control is not enabled for the database.
** Read and write access to data and configuration is unrestricted.
8.1、创建用户使用密码登录,并启用访问控制
创建用户
use admin
db.createUser({user:"test",pwd:"123456",roles:["root"]})
# db.createUser({user:"test",pwd:"123456",roles:[{role:"root",db:"admin"}]})
# db.createUser({user:"user",pwd:"123456",roles:[{role:"dbOwner",db:"testdb"}]})
# 结果
Successfully added user: { "user" : "test", "roles" : [ "root" ] }
启用访问控制
vim /usr/local/soft/mongodb/conf/conf/mongod.conf
# 开启配置
security:
authorization: enabled
使用密码登录
./mongo -utest -p123456
查看用户
use admin
db.system.users.find()
# show users
# 结果
{ "_id" : "admin.test", "userId" : UUID("3f0d69a0-df7e-4c3d-8613-ec7d5772a40b"), "user" : "test", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "Ph7rl4vRqyfvMRhsQlR+lA==", "storedKey" : "tccUlVg2T5E1Ne8SqVDlrxQV82I=", "serverKey" : "IvEGbgc+amky9M19PAVJ2sGZ7MA=" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "OO2BvYfg/uRvEBMeOvAG6gfnrJ+9Ro07QqmouQ==", "storedKey" : "Gc47E/DOz/T22TWKZaN9hOaLB948VHsnxQWpE54Ljmk=", "serverKey" : "FN1NWxzloDkQquKZ/rL+bsVFmaEvUhXTMfVMyVIRoUo=" } }, "roles" : [ { "role" : "root", "db" : "admin" } ] }