centos8 安裝mongodb4.4
centos8 安裝mongodb4.4
配置yum源
cd /etc/yum.repos.d
vi /etc/yum.repos.d/mongodb.repo
[mongodb-org]
name=MongoDB Repository
baseurl=https://mirrors.tuna.tsinghua.edu.cn/mongodb/yum/el$releasever/
gpgcheck=0
enabled=1
安裝
sudo yum makecache
sudo yum install mongodb-org
啟動mongodb 並設定開機啟動
[root@localhost yum.repos.d]# systemctl status mongod ● mongod.service - MongoDB Database Server Loaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; vendor preset: disabled) Active: inactive (dead) Docs: https://docs.mongodb.org/manual [root@localhost yum.repos.d]# systemctl start mongod [root@localhost yum.repos.d]# systemctl enable mongod
檢查MongoDB的服務狀態和埠監聽資訊
[root@mongodb ~]# systemctl status mongod.service ● mongod.service - MongoDB Database Server Loaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; vendor preset: disabled) Active: active (running) since Fri 2020-12-18 23:17:49 CST; 16s ago Docs: https://docs.mongodb.org/manual Process: 930807 ExecStart=/usr/bin/mongod $OPTIONS (code=exited, status=0/SUCCESS) Process: 930804 ExecStartPre=/usr/bin/chmod 0755 /var/run/mongodb (code=exited, status=0/SUCCESS) Process: 930802 ExecStartPre=/usr/bin/chown mongod:mongod /var/run/mongodb (code=exited, status=0/SUCCESS) Process: 930800 ExecStartPre=/usr/bin/mkdir -p /var/run/mongodb (code=exited, status=0/SUCCESS) Main PID: 930809 (mongod) Memory: 57.7M CGroup: /system.slice/mongod.service └─930809 /usr/bin/mongod -f /etc/mongod.conf Dec 18 23:17:48 mongodb.lianglab.cn systemd[1]: Starting MongoDB Database Server... Dec 18 23:17:48 mongodb.lianglab.cn mongod[930807]: about to fork child process, waiting until server is ready for connections. Dec 18 23:17:48 mongodb.lianglab.cn mongod[930807]: forked process: 930809 Dec 18 23:17:49 mongodb.lianglab.cn mongod[930807]: child process started successfully, parent exiting Dec 18 23:17:49 mongodb.lianglab.cn systemd[1]: Started MongoDB Database Server [root@mongodb ~]# netstat -anplt| grep mongod tcp 0 0 127.0.0.1:27017 0.0.0.0:* LISTEN 930809/mongod [root@mongodb ~]# ss -anplt | grep mongod LISTEN 0 128 127.0.0.1:27017 0.0.0.0:* users:(("mongod",pid=930809,fd=12))
CentOS 8上為MongoDB建立SELinux策略:
根據MongoDB文件,如果您已將SELinux配置為強制模式,則必須為MongoDB建立SELinux策略。
檢查當前的SELinux模式。
[root@mongodb ~]# getenforce
Enforcing
我們需要checkpolicy命令來驗證自定義SELinux策略,因此我們正在使用dnf命令安裝checkpolicy軟體包。
[root@mongodb ~]#dnf install -y checkpolicy CentOS-8 - AppStream 4.0 kB/s | 4.3 kB 00:01 CentOS-8 - Base 3.0 kB/s | 3.8 kB 00:01 CentOS-8 - Extras 2.7 kB/s | 1.5 kB 00:00 MongoDB Repository 1.6 kB/s | 2.5 kB 00:01 Dependencies resolved. ================================================================================ Package Architecture Version Repository Size ================================================================================ Installing: checkpolicy x86_64 2.9-1.el8 BaseOS 348 k Transaction Summary ================================================================================ Install 1 Package Total download size: 348 k Installed size: 1.7 M Downloading Packages: checkpolicy-2.9-1.el8.x86_64.rpm 7.5 kB/s | 348 kB 00:46 -------------------------------------------------------------------------------- Total 7.5 kB/s | 348 kB 00:46 Running transaction check Transaction check succeeded. Running transaction test Transaction test succeeded. Running transaction Preparing : 1/1 Installing : checkpolicy-2.9-1.el8.x86_64 1/1 Running scriptlet: checkpolicy-2.9-1.el8.x86_64 1/1 Verifying : checkpolicy-2.9-1.el8.x86_64 1/1 Installed: checkpolicy-2.9-1.el8.x86_64 Complete!
建立一個定製的SELinux策略檔案。
[root@mongodb ~]# vi mongodb_cgroup_memory.te
並在其中新增以下指令。
module mongodb_cgroup_memory 1.0;
require {
type cgroup_t;
type mongod_t;
class dir search;
class file { getattr open read };
}
#============= mongod_t ==============
allow mongod_t cgroup_t:dir search;
allow mongod_t cgroup_t:file { getattr open read };
編譯並應用此SELinux策略。
[root@mongodb ~]# checkmodule -M -m -o mongodb_cgroup_memory.mod mongodb_cgroup_memory.te
[root@mongodb ~]# semodule_package -o mongodb_cgroup_memory.pp -m mongodb_cgroup_memory.mod
[[root@mongodb ~]# semodule -i mongodb_cgroup_memory.pp
建立admin賬號
[root@localhost ~]# mongo
MongoDB shell version v4.4.6
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("2df728ce-2a97-4635-b9c5-81e0f00923c6") }
MongoDB server version: 4.4.6
---
The server generated these startup warnings when booting:
2021-06-29T20:42:30.610+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
2021-06-29T20:42:30.611+08:00: /sys/kernel/mm/transparent_hugepage/enabled is 'always'. We suggest setting it to 'never'
---
---
Enable MongoDB's free cloud-based monitoring service, which will then receive and display
metrics about your deployment (disk utilization, CPU, operation statistics, etc).
The monitoring data will be available on a MongoDB website with a unique URL accessible to you
and anyone you share the URL with. MongoDB may use this information to make product
improvements and to suggest MongoDB products and deployment options to you.
To enable free monitoring, run the following command: db.enableFreeMonitoring()
To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---
> use admin;
switched to db admin
> db.createUser(
... {
... user: "admin",
... pwd: "liang123",
... roles: [ { role: "userAdminAnyDatabase",db: "admin" } ]
... }
... )
Successfully added user: {
"user" : "admin",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
]
}
> show users
{
"_id" : "admin.admin",
"userId" : UUID("91c06ceb-0dc4-4687-a467-679a9a8c75fa"),
"user" : "admin",
"db" : "admin",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
> exit
bye
[root@localhost ~]#
MongoDB伺服器中啟用訪問控制:
最初,訪問控制在MongoDB伺服器中被禁用。因此,任何具有CentOS 8伺服器作業系統級訪問許可權的使用者都可以連線到MongoDB例項並在資料庫上執行管理操作。這就是為什麼我們能夠在上一步中建立管理員使用者而無需任何身份驗證的原因。
要為MongoDB伺服器啟用訪問控制,我們需要為mongod.service編輯systemd單元檔案。
[root@mongodb ~]# vi /usr/lib/systemd/system/mongod.service
在此檔案中找到以下行。
Environment="OPTIONS=-f /etc/mongod.conf"
並將其替換為以下行。
Environment="OPTIONS=--auth -f /etc/mongod.conf"
我們已經使用文字編輯器顯式地編輯了systemd單位檔案。因此,我們需要執行以下命令來通知systemd有關此更改。
[root@mongodb ~]# systemctl daemon-reload
重新啟動MongoDB服務以應用更改。
[root@mongodb ~]# systemctl restart mongod.service
要檢查訪問控制,請連線MongoDB shell並執行一些管理命令。
[root@localhost ~]# mongo
MongoDB shell version v4.4.6
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("d07e43a9-d2f5-4884-b9df-962f76fa7b77") }
MongoDB server version: 4.4.6
> use admin;
switched to db admin
> show users;
uncaught exception: Error: command usersInfo requires authentication :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DB.prototype.getUsers@src/mongo/shell/db.js:1659:15
shellHelper.show@src/mongo/shell/utils.js:914:9
shellHelper@src/mongo/shell/utils.js:819:15
@(shellhelp2):1:1
>
這次“ show user”命令引發身份驗證錯誤,它確認在我們的MongoDB伺服器中已啟用訪問控制。
現在,以管理員使用者身份連線。
> db.auth("admin",passwordPrompt())
Enter password:
1
> show users
{
"_id" : "admin.admin",
"userId" : UUID("91c06ceb-0dc4-4687-a467-679a9a8c75fa"),
"user" : "admin",
"db" : "admin",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
>
已成功使用特權使用者執行命令“顯示使用者”。
MongoDB資料庫的訪問控制已啟用。
配置MongoDB服務以進行網路訪問:
此步驟是可選的。如果您打算通過網路訪問MongoDB資料庫,則必須執行以下配置。
預設情況下,MongoDB服務在本地主機介面上執行。因此,要使其能夠從網路訪問,我們需要在所有介面上執行MongoDB服務。
使用vim編輯器編輯MongoDB配置檔案
vi /etc/mongod.conf
# network interfaces
net:
port: 27017
# bindIp: 127.0.0.1 # Enter 0.0.0.0,:: to bind to all IPv4 and IPv6 addresses or, alternatively, use the net.bindIpAll setting.
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.
重新啟動MongoDB服務以應用更改。
[root@localhost ~]# systemctl restart mongod.service
防火牆設定
設定如果我們啟動了防火牆策略,還需要允許Linux防火牆中的MongoDB服務傳入流量。
[root@mongodb ~]#firewall-cmd --permanent --add-service=mongodb
success
[root@mongodb ~]# firewall-cmd --reload
success
您現在可以從網路訪問MongoDB資料庫服務。
MongoDB資料和日誌目錄:
以下是兩個目錄,對MongoDB資料庫管理員來說非常重要。
- /var/lib/mongo-資料目錄(預設)
- /var/log/mongodb-日誌目錄(預設)
我們可以通過在/etc/mongodb.conf檔案中設定以下引數來自定義以上目錄。
- storage.dbPath-指定新的資料目錄路徑
- systemLog.path-指定新的日誌檔案路徑
基本用法
檢視
show dbs 檢視資料庫
use dbname 進入資料庫
show users 檢視當前資料庫使用者許可權
建立使用者
db.createUser({user:"usertest",pwd:"passtest",roles:[ {role:"clusterAdmin", db:"admin" }, {role:"readAnyDatabase",db:"admin" }, {role:"readWrite",db:"testDB" } ]})
許可權詳解
內建角色:
資料庫使用者角色:read、readWrite;
資料庫管理角色:dbAdmin、dbOwner、userAdmin;
叢集管理角色: clusterAdmin、clusterManager、clusterMonitor、hostManager;
備份恢復角色: backup、restore;
所有資料庫角色:readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase
超級使用者角色: root; 這裡還有幾個角色間接或直接提供了系統超級使用者的訪問(dbOwner 、userAdmin、userAdminAnyDatabase)
內部角色: __system;
------------------------------------------------------------------------------------------
角色說明:
Read: 允許使用者讀取指定資料庫
readWrite: 允許使用者讀寫指定資料庫
dbAdmin: 允許使用者在指定資料庫中執行管理函式,如索引建立、刪除,檢視統計或訪問system.profile
userAdmin: 允許使用者向system.users集合寫入,可以找指定資料庫裡建立、刪除和管理使用者
dbOwner: 允許在當前DB中執行任意操作
readAnyDatabase: 賦予使用者所有資料庫的讀許可權,只在admin資料庫中可用
readWriteAnyDatabase: 賦予使用者所有資料庫的讀寫許可權,只在admin資料庫中可用
userAdminAnyDatabase:賦予使用者所有資料庫管理User的許可權,只在admin資料庫中可用
dbAdminAnyDatabase: 賦予管理所有資料庫的許可權,只在admin資料庫中可用
root: 超級賬號,超級許可權,只在admin資料庫中可用。
------------------------------------------------------------------------------------------
叢集管理角色:
clusterAdmin: 賦予管理叢集的最高許可權,只在admin資料庫中可用
clusterManager: 賦予管理和監控叢集的許可權
clusterMonitor: 賦予監控叢集的許可權,對監控工具具有readonly的許可權
hostManager: 賦予管理Server
修改密碼
方法1:db.changeUserPassword("usertest","changepass");
方法2:db.updateUser("usertest",{pwd:"changepass1"});
修改許可權
db.updateUser("usertest",{roles:[ {role:"read",db:"testDB"} ]})
注:updateuser它是完全替換之前的值,如果要新增或新增roles而不是代替它
則使用方法: db.grantRolesToUser() 和 db.revokeRolesFromUser()
------------------------------------------------------------------------------------------
db.grantRolesToUser("usertest", [{role:"readWrite", db:"testDB"},{role:"read", db:"testDB"}]) # 修改許可權
db.revokeRolesFromUser("usertest",[{role:"read", db:"testDB"}]) # 刪除許可權:
刪除使用者
db.dropUser('usertest')
參考:
https://jingyan.baidu.com/article/dca1fa6f0428a4f1a440522e.html