CentOS 7.9 MongoDB 安装和使用

CentOS 7.9 MongoDB 安装和使用

一、软件下载及安装

说明:CentOS 版本有RedHat / CentOS 7.0RedHat / CentOS 7.2 s390x,建议下载与操作系统CPU架构一致的软件安装包,以保证兼容性和高性能。输入arch可查看操作系统CPU架构。

注意:CentOS 7.9 与 mongodb 5.0.x不兼容,请安装mongodb 4.4.x

s390x架构: s390x 是 IBM System z 系列 (zSeries)大型机 (mainframe) 硬件平台,是银行或者大型企业或者科研单位用的,大部分用户接触不到。

下载地址

mongodb官网安装手册

下载

cat > /etc/yum.repos.d/mongodb-org-4.4.repo <<\EOF
[mongodb-org-4.4]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.4/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-4.4.asc

EOF
sudo yum install -y mongodb-org

若要安装指定版本,需使用以下命令

sudo yum install -y mongodb-org-4.4.8 mongodb-org-server-4.4.8 mongodb-org-shell-4.4.8 mongodb-org-mongos-4.4.8 mongodb-org-tools-4.4.8
依赖关系解决

===========================================================================================================================================================
 Package                                             架构                      版本                               源                                  大小
===========================================================================================================================================================
正在安装:
 mongodb-org                                         x86_64                    4.4.10-1.el7                       mongodb-org-4.4                    6.2 k
为依赖而安装:
 mongodb-org-database-tools-extra                    x86_64                    4.4.10-1.el7                       mongodb-org-4.4                     19 k
 mongodb-org-mongos                                  x86_64                    4.4.10-1.el7                       mongodb-org-4.4                     17 M
 mongodb-org-server                                  x86_64                    4.4.10-1.el7                       mongodb-org-4.4                     22 M
 mongodb-org-shell                                   x86_64                    4.4.10-1.el7                       mongodb-org-4.4                     14 M
 mongodb-org-tools                                   x86_64                    4.4.10-1.el7                       mongodb-org-4.4                    6.1 k

事务概要
===========================================================================================================================================================
安装  1 软件包 (+5 依赖软件包)

总下载量:52 M
安装大小:192 M

MongoDB Community Edition Packages

MongoDB Community Edition is available from its own dedicated repository, and contains the following officially-supported packages:

Package NameDescription
mongodb-orgA metapackage that automatically installs the component packages listed below.
mongodb-org-databaseA metapackage that automatically installs the component packages listed below.Package NameDescriptionmongodb-org-serverContains the mongod daemon, associated init script, and a configuration file (/etc/mongod.conf). You can use the initialization script to start mongod with the configuration file. For details, see the “Run MongoDB Community Edition” section, above.mongodb-org-mongosContains the mongos daemon.mongodb-org-shellContains the legacy mongo shell.
mongodb-mongoshContains the MongoDB Shell (mongosh).
mongodb-org-toolsA metapackage that automatically installs the component packages listed below:Package NameDescriptionmongodb-database-toolsContains the following MongoDB database tools:mongodumpmongorestorebsondumpmongoimportmongoexportmongostatmongotopmongofilesmongodb-org-database-tools-extraContains the install_compass script

二、系统配置

Starting in MongoDB 4.4, a startup error is generated if the ulimit value for number of open files is under 64000.

1.limits设置

cat > /etc/security/limits.d/mongod.conf <<\EOF
mongod soft nproc 2047
mongod hard nproc 16384
mongod soft nofile 10240
mongod hard nofile 65535

EOF

2.防火墙设置

firewall-cmd --zone=public --add-port=27017/tcp --permanent
firewall-cmd --reload

3.关闭SeLinux

sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
sed -i 's/SELINUX=permissive/SELINUX=disabled/g' /etc/selinux/config
setenforce 0
getenforce

selinux配置

4.禁用transparent_hugepage

自CentOS6版本开始引入了Transparent Huge Pages(THP),从CentOS7版本开始,该特性默认就会启用。尽管THP的本意是为提升内存的性能,不过某些数据库厂商还是建议直接关闭THP(比如说ORACLE、MariaDB、MongoDB等),否则可能会导致性能出现下降。

cat >> /etc/rc.d/rc.local <<\EOF
if test -f /sys/kernel/mm/transparent_hugepage/enabled; then
echo never > /sys/kernel/mm/transparent_hugepage/enabled
fi
if test -f /sys/kernel/mm/transparent_hugepage/defrag; then
echo never > /sys/kernel/mm/transparent_hugepage/defrag
fi


EOF
source /etc/rc.d/rc.local

三、软件配置

1.数据目录

  • /var/lib/mongo (the data directory)
  • /var/log/mongodb (the log directory)
mkdir -p /home/data/mongodb/log
mkdir -p /home/data/mongodb/data
sudo chown -R mongod:mongod /home/data/mongodb

/etc/mongod.conf中的storage.dbPathsystemLog.path 分别改为上面的路径。

2.开放访问IP

/etc/mongod.conf中bindIp由127.0.0.1改为0.0.0.0

# network interfaces
net:
  port: 27017
  bindIp: 0.0.0.0  # Enter 0.0.0.0,:: to bind to all IPv4 and IPv6 addresses or, alternatively, use the net.bindIpAll setting.

四、启动和关闭服务

1.启动

sudo systemctl start mongod

2.状态

sudo systemctl status mongod

3.关闭

sudo systemctl stop mongod

4.开机启动

sudo systemctl enable mongod

五、卸载

sudo yum erase $(rpm -qa | grep mongodb-org)
sudo rm -r /var/log/mongodb
sudo rm -r /var/lib/mongo

六、使用

1.免费云监控

打开云监控db.enableFreeMonitoring(),注意与监控页面在mongodb官网,因此需要服务器连接外网。

mongo
> db.enableFreeMonitoring()
{
        "state" : "enabled",
        "message" : "To see your monitoring data, navigate to the unique URL below. Anyone you share the URL with will also be able to view this page. You can disable monitoring at any time by running db.disableFreeMonitoring().",
        "url" : "https://cloud.mongodb.com/freemonitoring/cluster/随机ID",
        "userReminder" : "",
        "ok" : 1
}
db.disableFreeMonitoring()

2.添加用户、安全认证

enable-authentication

db.getUser

mongo

> db
test
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
> use admin
switched to db admin
> db
admin
> db.createUser(
  {
    user: "root",
    pwd: passwordPrompt(), // or cleartext password
    roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
  }
)

> use test
> db.createUser(
  {
    user: "test",
    pwd:  passwordPrompt(),   // or cleartext password
    roles: [ { role: "readWrite", db: "test" },
             { role: "read", db: "reporting" } ]
  }
)

> db.shutdownServer()
server should be down...
>
  • 启用认证

vim /etc/mongod.conf追加以下内容

security:
    authorization: enabled
  • client认证
mongo -umyUserAdmin -p
mongo --port 27017 -u "test" --authenticationDatabase "test" -p

注意:先切换到对应的数据库(例如use admin),再执行db.auth()认证(查询、删除等操作也是如此)。

mongo
> db.auth('test')
  • 查询用户
mongo -uroot -p
> use admin
switched to db admin
> db.getUsers()
  • 删除用户
> db.dropUser('test')
  • 修改密码
db.updateUser('test',{pwd: passwordPrompt()})
  • 超级管理员
db.createUser(
   {
     user: "superuser",
     pwd: "123456",
     
     roles: [{"role":"root","db":"admin"}],
    /* All built-in Roles 
     Database User Roles: read|readWrite
     Database Admin Roles: dbAdmin|dbOwner|userAdmin
     Cluster Admin Roles: clusterAdmin|clusterManager|clusterMonitor|hostManager
     Backup and Restoration Roles: backup|restore
     All-Database Roles: readAnyDatabase|readWriteAnyDatabase|userAdminAnyDatabase|dbAdminAnyDatabase
     Superuser Roles: root 
    */
    
     // authenticationRestrictions: [ {
     //       clientSource: ["192.0.2.0"],
     //       serverAddress: ["198.51.100.0"]
     // } ],
     //mechanisms: [ "SCRAM-SHA-1","SCRAM-SHA-256"], 
     //passwordDigestor: "server|client",
   }
)

3.database-tools

database-tools 官方文档

命令说明
Binary Import / Export
mongodumpCreates a binary export of the contents of a mongod database.
mongorestoreRestores data from a mongodump database dump into a mongod or mongos
bsondumpConverts BSON dump files into JSON.
Data Import / Export
mongoimportImports content from an Extended JSON, CSV, or TSV export file.
mongoexportProduces a JSON or CSV export of data stored in a mongod instance.
Diagnostic Tools
mongostatProvides a quick overview of the status of a currently running mongod or mongos instance.
mongotopProvides an overview of the time a mongod instance spends reading and writing data.
GridFS Tools
mongofilesSupports manipulating files stored in your MongoDB instance in GridFS objects.
  • mongotop
cat > /etc/mongod.yaml <<\EOF
password: 123456
uri: mongodb://superuser@localhost:27017/?authSource=admin
sslPEMKeyPassword: 123456

EOF
mongotop --config=/etc/mongod.yaml
  • mongodump (备份)
mongodump --config=/etc/mongod.yaml --archive=mongodump-test-db.archive --db=test

启用压缩

mongodump --config=/etc/mongod.yaml --archive=mongodump-test-db.gz --gzip --db=test
  • mongorestore (恢复)
mongorestore --config=/etc/mongod.yaml  --archive=mongodump-test-db.archive --nsFrom='test.*' --nsTo='example.*'
  • mongodump (bson=>json)
mongodump --config=/etc/mongod.yaml --db=test -o dump
cd ./dump/
bsondump --pretty --outFile=testCollection.json testCollection.bson

七、客户端连接工具

nosqlbooster4mongo

nosqlbooster 针对MongoDB的最智能的IDE工具, 30天免费使用期限,到期自动转免费版(功能限制)。

九、遇到问题

  • CentOS 7.9安装mongodb 5.0.x后无法启动,报如下错误:
Nov 11 12:14:02 node-1 systemd: Starting MongoDB Database Server...
Nov 11 12:14:02 node-1 kernel: traps: mongod[83285] trap invalid opcode ip:5568d174ddfa sp:7ffebad6dfc0 error:0 in mongod[5568cd810000+5055000]
Nov 11 12:14:02 node-1 abrt-hook-ccpp: Process 83285 (mongod) of user 991 killed by SIGILL - dumping core
Nov 11 12:14:02 node-1 systemd: mongod.service: control process exited, code=dumped status=4
Nov 11 12:14:02 node-1 systemd: Failed to start MongoDB Database Server.
Nov 11 12:14:02 node-1 systemd: Unit mongod.service entered failed state.
Nov 11 12:14:02 node-1 systemd: mongod.service failed.
Nov 11 12:14:02 node-1 abrt-server: Package 'mongodb-org-server' isn't signed with proper key
Nov 11 12:14:02 node-1 abrt-server: 'post-create' on '/var/spool/abrt/ccpp-2021-11-11-12:14:02-83285' exited with 1
Nov 11 12:14:02 node-1 abrt-server: Deleting problem directory '/var/spool/abrt/ccpp-2021-11-11-12:14:02-83285'
  • 解决办法

降低mongodb版本号,改用mongodb 4.4.x(或者使用tar.gz包方式安装)。

参考:

i386 、x86_64 、ppc是指CPU的架构](https://www.cnblogs.com/wangwangever/articles/7649603.html)

mongodb linux官网安装教程

Linux安装mongodb数据库最新版(全网最细)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

搬山境KL攻城狮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值