MongoDB
MongoDBBearbeiten- LernenFür das tiefergreifende Selbststudium empfiehlt sich die MongoDB University zu besuchen. Der Kurs M102 eignet sich zum Einstieg.
https://university.mongodb.com/courses/M102/about
Bearbeiten- InstallationBearbeiten- Nutzer wechselnAlles als Nutzer mongouser durchführen
su - mongouserBearbeiten- Ordner Anlegenmkdir /srv/mongodb/log mkdir /srv/mongodb/db
Bearbeiten- Download tarball und entpackenwget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.4.1.tgz#nach /srv/mongodb entpacken ( z.B.: /srv/mongodb/mongodb-linux-x86_64-3.4.1 )
cd /srv/mongodb ; tar xvfz mongodb-linux-x86_64-3.4.1.tgzBearbeiten- Konfiguration und Scripte anlegen/srv/mongodb/mongodb.configsystemLog: destination: file path: „/srv/mongodb/log/mongodb.log“ logAppend: true logRotate: rename storage: dbPath: „/srv/mongodb/db“ journal:
enabled: trueprocessManagement:
fork: truenet:
bindIp: 127.0.0.1port: 27017setParameter:
enableLocalhostAuthBypass: falseBearbeiten- Shutdown Skript/srv/mongodb/shutdown.sh (chmod +x)
#!/bin/shexport MONGODB_BASE=/srv/mongodbexport MONGODB_DIR=$MONGODB_BASE/mongodb-linux-x86_64-3.4.1export MONGODB_CONFIG_FILE=$MONGODB_BASE/mongodb.configexport PATH=$MONGODB_DIR/bin:$PATHif [ $(whoami) = 'mts' ]; then ${MONGODB_DIR}/bin/mongod --shutdown --config $MONGODB_CONFIG_FILE echo " stopped." else echo "Error - MongoDB will not shutdown with user $USER!"fiBearbeiten- Startup Skript/srv/mongodb/startup.sh (chmod +x)
#!/bin/shexport MONGODB_BASE=/srv/mongodbexport MONGODB_DIR=$MONGODB_BASE/mongodb-linux-x86_64-3.4.1export MONGODB_CONFIG_FILE=$MONGODB_BASE/mongodb.configexport PATH=$MONGODB_DIR/bin:$PATHif [ $(whoami) = 'mts' ]; then ${MONGODB_DIR}/bin/mongod --config $MONGODB_CONFIG_FILE echo "MongoDB started." else echo "Error - MongoDB will not start up with user $USER!"fiBearbeiten- Logrotate/srv/mongodb/logrotate.sh (chmod +x)
#!/bin/shexport MONGODB_BASE=/srv/mongodbexport MONGODB_DIR=$MONGODB_BASE/mongodb-linux-x86_64-3.4.1export PATH=$MONGODB_DIR/bin:$PATHif [ $(whoami) = 'mts' ]; then ${MONGODB_DIR}/bin/mongo < $MONGODB_BASE/logrotate.js echo "MongoDB logs rotated."else echo "Error - MongoDB will not rotate logs with user $USER!"fi/srv/mongodb/logrotate.js
use admindb.runCommand( { logRotate : 1 } )exitCronjob für den MongoDB Funktionsnutzer einrichten
$ su - mts$ crontab -e# folgende Zeile einfügen (für wöchentliche Logs am Montag um Mitternacht):
0 0 * * 1 /srv/mongodb/logrotate.sh > /dev/null 2>&1Bearbeiten- Init.d/etc/init.d/mongodb-server (chmod +x)
Zum Anzeigen hier klicken ⇲
Anschließend in den Autostart setzen, damit der MongoDB Server beim Reboot auch gestartet wird.
Ubuntu:
update-rc.d mongodb-server defaultsRedHat:
chkconfig --add mongodb-serverBearbeiten- Benutzer und DB anlegenQuelle: https://dev-tek.de/lexicon/entry/60-mongodb-anleitung-authentication-aktivieren-und-benutzer-anlegen/
cd /srv/mts/mongodb/mongodb-linux-x86_64-3.4.1/bin/./mongooder wenn als Dienst installiert, dann einfach
mongo
Zuerst User mit Admin-Rechten anlegen und für „Admin“ DB berechtigen, xxxx muss ausgefüllt werden
db.createUser(
{
user: "superadmin",
pwd: "adminpasswort",
roles: [ { role: "root", db: "admin" } ]
}
)
Eigene Datenbank und neuen Benutzer anlegen (vorher authentifizieren mit admin-Benutze)
bash: # mongo
rs0:PRIMARY> use admin
switched to db admin
rs0:PRIMARY> db.auth("superadmin","adminpasswort")
z.B.
db.createUser({ user: "lernintranet", pwd: "hnfd76fdde", roles: [ { role: "readWrite", db: "lernintranetdb-test" }]})
Danach speichern
db.users.save( {username:"lernintranet"} )
Datenbank anzeigen
show dbs
In der mongodb.config muss folgendes hinzugefügt werden:
mongosh --username lernintranet --password --authenticationDatabase lernintranetdb-int --host 127.0.0.1 --port 27017
MongoDB shell version v3.6.17
Enter password:
connecting to: mongodb://127.0.0.1:27017/?authSource=lernintranetdb-int&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("d4aa8989-0c2f-4330-a786-df061513") }
MongoDB server version: 3.6.17
Dump
mongodump --db intranet --username superadmin --password "PASSWORTKEEPASS" --authenticationDatabase admin --gzip --out /tmp/`date +"%Y-%m-%d"
Dump in Docker
docker exec -i mongodb /usr/bin/mongorestore --username superadmin --password "geheim" --gzip --authenticationDatabase admin /data/dumps/mongodump-20220405
Bearbeiten
- Optional: Hochverfügbarkeit mittels Replicaset realisieren
Quelle: https://docs.mongodb.com/manual/tutorial/deploy-replica-set/
Zuerst eine ganz normale einzelne MongoDB Instanz installieren/starten
Dann Keyfile erzeugen, damit die Replicaset Nodes sich untereinander authentifizieren können Verzeichnisse und Keyfile erstellen
$ mkdir -p /pfad/zur/mongodb/keyfile
$ cd $MONGODB_HOME/keyfile
$ openssl rand -base64 741 > mongodb-keyfile
$ chmod 600 mongodb-keyfile
MongoDB Instanz mit Keyfile ausrüsten
In der mongodb.config nun das Replicaset aktivieren
replication:
replSetName: rs0
Replicaset initialisieren
rs.initiate({_id:"rs0",members:[{_id:0,host:"intranetdbt01.foo.network:27017"}]})
Replicaset Status abfragen
rs.status()
!! Zweite und dritte MongoDB Node starten (inkl. security authorization und keyfile Einstellung) !!
Zweite und driuttedritte Node in Replicaset aufnehmen von der ersten Node (PRIMARY) aus
rs.add("intranetdbt01.foo.network:27018")
rs.add("intranetdbt01.foo.network:27019")
Verbindung testen
$ mongo --host rs0/intranetdbt01.foo.network:27017,intranetdbt01.foo.network:27018,intranetdbt01.foo.network:27019
Berechtigungen setzen
Wenn ein Benutzer auf mehrere Datenbankschemas Zugriff bekommen soll
per mongosh (mongo-shell) anmelden
use admin;
db.auth('superadmin','geheim');
db.grantRolesToUser( "mein-user", [ { role: "readWrite", db: "bla_service" },{ role: "readWrite", db: "blabla_server" },{ role: "readWrite", db: "email_service" } ]);
Wenn mehrere Benutzer unterscheidliche Berechtigg. auf Datenbankschemen bekommen soll
per mongosh (mongo-shell) anmelden
db.grantRolesToUser( "BENUTZERNAME", [ { role: "BERECHTIGUNG", db: "DATENBANKNAME" }]);
use admin;
db.auth('superadmin','geheim');
db.grantRolesToUser( "bla_service", [ { role: "readWrite", db: "bla_service" }]);
db.grantRolesToUser( "blabla_service", [ { role: "readWrite", db: "blabla_service" }]);
db.grantRolesToUser( "email_service", [ { role: "readWrite", db: "email_service" }]);
Dump aller Datenbanken
mongodump --username superadmin --password "PASSWORTKEEPASS" --authenticationDatabase admin --gzip --archive=/Pfad/zum/Ausgabeordner/backup.gz
Backup-Skript für Docker
#!/bin/bash
USER="superadmin"
PASSWORD="geheim"
OUTPUT="/srv/exx/z_backups/mongodb"
DATABASE="cloud-prod-mongodb"
CONTAINER="mongodb"
DATE=$(date +%Y-%m-%d)
MAILTO="[email protected]"
# CREATE BACKUP DIR
if [ ! -d "$OUTPUT" ]; then
mkdir -p "$OUTPUT"
fi
rm -rf "$OUTPUT/$DATABASE*"
docker exec "$CONTAINER" mongodump --username "$USER" --password "$PASSWORD" --authenticationDatabase admin --gzip --archive="/data/dumps/$DATABASE.gz"
if [ "$?" -eq "0" ]; then
echo "DB Backup erfolgreich"
else
echo "DB Backup $DATABASE - $DATE fehlgeschlagen" | \
mail -s "$hostname - DB Backup $DATABASE fehlgeschlagen" -- "$MAILTO"
fi
Wiederherstellung
Im folgenden Befehl wieder die komplette DB vorher gelöscht (drop) und das Archiv wieder eingespielt.
Im docker-compose.yml sollte der Pfad "Input" auf einen Pfad der sich auf dem Host befindet verknüpft sein. Ansonsten kann mongorestore nicht auf die Dump-Datei zugreifen
docker exec -i "$CONTAINER" mongorestore --username "$USER" --password "$PASSWORD" --authenticationDatabase admin --gzip --archive="$DATABASE.gz" --drop
#!/bin/bash
USER="superadmin"
PASSWORD="geheim"
INPUT="/data/dumps/"
DATABASE="cloud-prod-mongodb"
CONTAINER="mongodb"
docker exec -i "$CONTAINER" mongorestore --username "$USER" --password "$PASSWORD" --authenticationDatabase admin --gzip --archive="$INPUT/$DATABASE.gz" --drop