- Prerequisites
- Installing MongoDB
- Configuring MongoDB
- Securing MongoDB
- Starting and Managing MongoDB
- Setting Up Users and Authentication
- Configuring Firewall
- Initializing Replica Set
- Restoring Data
- Troubleshooting
- A Ubuntu server (this guide uses Ubuntu 22.04)
- Root or sudo access to the server
- Basic knowledge of terminal commands
-
Update the package list:
sudo apt-get update
-
Install required packages:
sudo apt-get install -y gnupg
-
Import the MongoDB public GPG key:
curl -fsSL https://pgp.mongodb.com/server-7.0.asc | \ sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg \ --dearmor
-
Create a list file for MongoDB:
echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
-
Update the package list again:
sudo apt-get update
-
Install MongoDB:
sudo apt-get install -y mongodb-org
-
Edit the MongoDB configuration file:
sudo nano /etc/mongod.conf
-
Here's a detailed
mongod.conf
file with explanations:# mongod.conf # Where and how to store data. storage: dbPath: /var/lib/mongodb journal: enabled: true # Where to write logging data. systemLog: destination: file logAppend: true path: /var/log/mongodb/mongod.log # Network interfaces net: port: 27017 bindIp: 0.0.0.0 # Allow connections from any IP # How the process runs processManagement: timeZoneInfo: /usr/share/zoneinfo # Security security: authorization: enabled keyFile: /etc/mongodb/keyfile # For replica set authentication # Replication replication: replSetName: "myReplicaSet"
Explanation of key settings:
storage.dbPath
: Where MongoDB stores its data filessystemLog
: Logging configurationnet.bindIp
:0.0.0.0
allows connections from any IPsecurity.authorization
: Enables access controlsecurity.keyFile
: Used for internal authentication in a replica setreplication.replSetName
: Name of the replica set
-
Save and exit the editor (in nano, press Ctrl+X, then Y, then Enter)
- Create a keyfile for replica set authentication:
sudo mkdir -p /etc/mongodb sudo openssl rand -base64 756 > /etc/mongodb/keyfile sudo chmod 400 /etc/mongodb/keyfile sudo chown mongodb:mongodb /etc/mongodb/keyfile
-
Start MongoDB:
sudo systemctl start mongod
-
Enable MongoDB to start on boot:
sudo systemctl enable mongod
-
Check MongoDB status:
sudo systemctl status mongod
-
Connect to MongoDB:
mongosh
-
Create an admin user:
use admin db.createUser( { user: "adminUser", pwd: "securePassword", // Change this! roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ] } )
-
Create a user for a specific database:
use test db.createUser( { user: "dpac", pwd: "securePassword", // Change this! roles: [ { role: "readWrite", db: "test" } ] } )
-
Allow MongoDB port through UFW:
sudo ufw allow from YOUR_IP_ADDRESS to any port 27017
Replace
YOUR_IP_ADDRESS
with the IP address you want to allow. -
Enable UFW if not already enabled:
sudo ufw enable
-
Check UFW status:
sudo ufw status
-
Connect to MongoDB:
mongosh
-
Initiate the replica set:
rs.initiate({ _id: "myReplicaSet", members: [ { _id: 0, host: "YOUR_SERVER_IP:27017" } ] })
Replace
YOUR_SERVER_IP
with your server's actual IP address.
- Restore data from a backup:
Replace
mongorestore --uri "mongodb://dpac:[email protected]:27017/test" --db test /path/to/backup/test/
securePassword
with the actual password for thedpac
user.
-
If MongoDB fails to start, check the logs:
sudo tail -n 100 /var/log/mongodb/mongod.log
-
If you encounter permission issues:
sudo chown -R mongodb:mongodb /var/lib/mongodb sudo chown -R mongodb:mongodb /var/log/mongodb
-
If you need to remove and reinstall MongoDB:
sudo apt-get purge mongodb-org* sudo rm -r /var/log/mongodb sudo rm -r /var/lib/mongodb
Then follow the installation steps again.
-
If you're having connection issues, ensure the bindIp in your mongod.conf is set correctly and that your firewall rules allow the connection.
Remember to replace placeholder passwords with strong, unique passwords in a production environment. Always follow best practices for security when setting up a database server.
This guide should help you set up a self-hosted MongoDB instance. Always refer to the official MongoDB documentation for the most up-to-date and comprehensive information.
MongoDB Replica Set Setup Guide
This guide provides step-by-step instructions for setting up a MongoDB replica set with security measures. The setup includes installing MongoDB, configuring the replica set, setting up authentication, and ensuring proper network security.
Table of Contents
Prerequisites
Installing MongoDB Community Edition
Perform these steps on all servers in your replica set.
Install required packages:
Import MongoDB GPG key:
curl -fsSL https://pgp.mongodb.com/server-7.0.asc | sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg --dearmor
Add MongoDB repository:
Update package list and install MongoDB:
Verify installation:
Start and enable MongoDB service:
sudo systemctl start mongod sudo systemctl enable mongod
Check MongoDB status and port:
sudo systemctl status mongod sudo ss -pnltu | grep 27017
Configuring Security Keyfile
Create a security keyfile on all servers:
Generate the keyfile:
openssl rand -base64 756 > /etc/mongodb-keyfile
Set proper permissions:
Verify the keyfile's SHA256 sum on all servers:
If the SHA256 sums are not identical across all servers, copy the keyfile from the primary to secondaries:
Create necessary directories:
Configuring MongoDB
Create data directory:
Edit MongoDB configuration file:
Update the following sections:
Restart MongoDB:
Initializing the Replica Set
Perform these steps on the primary server only.
Connect to MongoDB:
Initiate the replica set:
Creating Admin User
On the primary server:
Switch to admin database:
Create admin user:
Testing Primary and Secondary Nodes
Restart MongoDB on all servers:
Connect to primary:
mongosh "mongodb://admin:[email protected]:27017/admin?authSource=admin"
Connect to secondaries:
Check replica set status:
Changing Primary and Secondary Roles
To change the primary node:
Connect to the current primary:
Set priorities:
Reconfigure the replica set:
If necessary, force reconfiguration:
Optionally, step down the current primary:
Creating Application Database and Users
Create database and user:
Test data insertion:
Verify data replication:
Configuring Firewall
Use UFW (Uncomplicated Firewall) to secure your MongoDB servers:
Allow MongoDB port for specific IP:
Enable UFW:
sudo ufw enable
Check UFW status:
Troubleshooting
sudo tail -f /var/log/mongodb/mongod.log
Remember to replace placeholder values (like IP addresses and passwords) with your actual configuration details. Always use strong, unique passwords in production environments.