1.背景
为了避免出问题,采用的脚本在centos下一键安装。
2.需要的组件
请提前准备compat-openssl10-1.0.2o-3.el8.x86_64.rpm和mongodb-linux-x86_64-rhel70-4.2.3.tgz;
并将其提前放到linux的目录下。
注意:compat-openssl10-1.0.2o-3.el8.x86_64.rpm 可通过下面链接获取
compat-openssl10-1.0.2o-3.el8.x86_64.rpm-Linux文档类资源-CSDN下载
mongodb-linux-x86_64-rhel70-4.2.3.tgz 可通过下列命令获取
wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel70-4.2.3.tgz
3.脚本安装
直接使用命令执行 bash install_mongodb.sh 28222
注意:28222为端口,可根据自行修改,mongodb的config是加了端口后缀的。
nstall_mongodb.sh内容如下:
#!/bin/bash
# 修改第四行的下载版本mongodb-linux-x86_64-ubuntu1604-4.2.7.tgz和22行下载后的文件mongodb-linux-x86_64-ubuntu1604-4.2.7.tgz以及23行的解压后的文件目录mongodb-linux-x86_64-ubuntu1604-4.2.7
rpm -i compat-openssl10-1.0.2o-3.el8.x86_64.rpm
PORT=$1
result=`netstat -ntlp |grep -w "$PORT"|wc -l`
if [[ $result -eq 1 ]];then
echo "端口已被占用,请重新选择端口"
exit 1
fi
if [[ $PORT -lt 1000 || $PORT -gt 65535 ]];then
exit 2
fi
tar xf ./mongodb-linux-x86_64-rhel70-4.2.3.tgz
mv mongodb-linux-x86_64-rhel70-4.2.3 mongodb
cp -Ra ./mongodb /usr/local
echo "export PATH=$PATH:/usr/local/mongodb/bin" >> /etc/profile
source /etc/profile
groupadd mongodb
useradd mongodb -g mongodb
mkdir -p /data/mongodb && chown -R mongodb:mongodb /data/mongodb
cat > /usr/local/mongodb/mongodb_$PORT.conf <<EOF
port=$PORT #默认服务器端口号
dbpath=/data/mongodb #数据存储目录
logpath=/var/log/mongodb/mongodb_$PORT.log #日志文件
logappend=true #使用追加方式写日志
maxConns=5000 #最大连接数
bind_ip=0.0.0.0
EOF
cat > /lib/systemd/system/mongodb.service <<EOF
[Unit]
Description=MongoDB Database Server
Documentation=https://docs.mongodb.org/manual
After=network.target
[Service]
User=root
Group=root
ExecStart=/usr/local/mongodb/bin/mongod --quiet -f /usr/local/mongodb/mongodb_$PORT.conf
[Install]
WantedBy=multi-user.target
EOF
mkdir /var/log/mongodb && chown -R mongodb:mongodb /var/log/mongodb
systemctl daemon-reload
systemctl start mongodb.service
# 服务开机自启动
systemctl enable mongodb.service
4.密码设置
安装好mongodb后。输入命令
cd /usr/local/mongodb/bin
mongo 127.0.0.1:28222
use admin
db.createUser({user: "csdn", pwd: "123456CSDN*", roles: [{role: "root", db: "admin"}]})
上述操作后,退出数据库链接。回到Linux操作界面。输入下面的命令
vim /lib/systemd/system/mongodb.service
按照下图所示 的这一行的末尾 加上 --auth
操作完成后,直接重启下机器。就可以了。
5.验证
使用下列命令登录mongodb
cd /usr/local/mongodb/bin
mongo --port 28222 -u "csdn" -p "123456CSDN*" --authenticationDatabase "admin"