mongo服務搭建和集群說明文檔
1.下載安裝mongodb
下載所需版本(mongodb-linux-x86_64-3.4.6)的mongodb 官方地址解壓安裝包并復制到目標目錄
tar -xzvf mongo*.tar.gz -C /usr/local
mv /usr/local/mongodb-linux-x86_64-3.4.6 /usr/local/mongodb
配置環(huán)境變量
echo "export PATH=/usr/local/mongodb/bin:$PATH" >> ~/.bashrc
source ~/.bashrc
2.配置mongod
創(chuàng)建mongod.conf官網(wǎng)文檔。以下ip地址和端口請根據(jù)情況更換
cat <<'EOF'>>/etc/mongod.conf
systemLog:
??destination: file
??path: "/var/log/mongod.log"
??logAppend: true
processManagement:
??fork: true
net:
??bindIp: 10.25.113.1
??port: 27018
storage:
??dbPath: "/mongodata"
#security:
# ?keyFile: "/mongodata/.keyfile"
replication:
??replSetName: 'mongoRepl'
#setParameter:
# ?enableLocalhostAuthBypass: true
EOF
啟動mongod
mongod -f /etc/mongod.conf
連上數(shù)據(jù)庫并切換到admin下創(chuàng)建具有’userAdminAnyDatabase’’clusterAdmin’權限的用戶
連接mongodb,進入mongodb的cli
mongo <ip>:<port>
使用admin
use admin
創(chuàng)建管理用用戶
db.createUser({user:"root",pwd:"Paic1234",roles:[{"role":"userAdminAnyDatabase","db":"admin"},{"role":"clusterAdmin","db":"admin"}]})
檢查
show users
3.集群搭建
生成.keyFile文件并修改文件權限
openssl rand -base64 756 > /mongodata/.keyfile
chmod 400 /mongodata/.keyfile
將生成好的.keyFile文件復制到各個服務節(jié)點下
開啟訪問控制,在mongod.conf中添加如下配置
security:
??keyFile: "/mongodata/.keyfile"
replication:
??replSetName: 'mongoRepl'
setParameter:
??enableLocalhostAuthBypass: true
重啟mongodb
pkill mongod
mongod -f /etc/mongod.conf
各節(jié)點保證mongodb的啟動,然后初始化集群,host中的主機域名和端口根據(jù)環(huán)境更改
rs.initiate(
??{
????id : 'mongoRepl',
??????members: [
????????{ _id : 0, host : "mongo1.example.net:27018" },
????????{ _id : 0, host : "mongo2.example.net:27018" },
????????{ _id : 0, host : "mongo3.example.net:27018" },
????????]
??}
)
通過rs.status()查看主從節(jié)點
注:在從節(jié)點下需要執(zhí)行rs.slaveOk()后才能執(zhí)行數(shù)據(jù)庫管理和用戶管理等操作。數(shù)據(jù)庫下需要執(zhí)行db.setSlaveOk()后才能對數(shù)據(jù)庫操作。
切換到相關數(shù)據(jù)庫下進行建權
4.數(shù)據(jù)備份和恢復
4.1 MongoDB數(shù)據(jù)庫備份
mongodump -h dbhost -d dbname -u user -p pwd -o dbdirectory
-h: MongDB所在服務器地址,例如:127.0.0.1,當然也可以指定端口號:127.0.0.1:27017
-d: 需要備份的數(shù)據(jù)庫實例,例如:test
-u:備份數(shù)據(jù)庫的用戶
-p:備份數(shù)據(jù)庫的密碼
-o: 備份的數(shù)據(jù)存放位置,例如:/home/mongodump/,當然該目錄需要提前建立,這個目錄里面存放該數(shù)據(jù)庫實例的備份數(shù)據(jù)。
4.2 MongoDB數(shù)據(jù)庫恢復
mongorestore -h dbhost -d dbname --dir dbdirectory
-h: MongoDB所在服務器地址
-d: 需要恢復的數(shù)據(jù)庫實例,例如:test,當然這個名稱也可以和備份時候的不一樣,比如test2
-u:需恢復數(shù)據(jù)庫的用戶
-p:需恢復數(shù)據(jù)庫的密碼
—dir: 備份數(shù)據(jù)所在位置,例如:/home/mongodump/itcast/
—drop: 恢復的時候,先刪除當前數(shù)據(jù),然后恢復備份的數(shù)據(jù)。就是說,恢復后,備份后添加修改的數(shù)據(jù)都會被刪除,慎用!
—authenticationDatabase: admin 需恢復數(shù)據(jù)庫admin庫進行授權恢復