How To Install MongoDB on AlmaLinux 10
MongoDB stands as one of the most popular NoSQL document databases in modern application development. Its flexibility, scalability, and performance make it an ideal choice for handling large volumes of unstructured data. AlmaLinux 10, being a community-driven enterprise Linux distribution based on Red Hat Enterprise Linux, provides a stable and secure foundation for running MongoDB in production environments.
This comprehensive guide walks you through multiple methods of installing MongoDB on AlmaLinux 10, ensuring you have the knowledge to deploy this powerful database system successfully. Whether you’re a developer setting up a development environment or a system administrator deploying MongoDB for enterprise applications, this tutorial covers everything from basic installation to advanced configuration and security hardening.
We’ll explore two primary installation approaches: using the official MongoDB repository for native installation and leveraging Docker containers for containerized deployments. Each method offers distinct advantages depending on your specific use case and infrastructure requirements.
Prerequisites and System Requirements
Before diving into the installation process, ensure your AlmaLinux 10 system meets the necessary requirements for running MongoDB effectively.
Hardware Requirements
MongoDB requires adequate system resources to function optimally. For development environments, allocate at least 2GB of RAM and 10GB of available disk space. Production deployments demand significantly more resources, with a recommended minimum of 8GB RAM and high-performance SSD storage for optimal database performance.
The CPU requirements vary based on workload, but modern multi-core processors handle MongoDB operations efficiently. Consider your expected concurrent connections and query complexity when sizing your hardware infrastructure.
Software Requirements
Your AlmaLinux 10 server must have internet connectivity for downloading packages and repositories. Root or sudo privileges are essential for installing packages, configuring services, and modifying system files. Ensure your system runs a clean AlmaLinux 10 installation with the latest security updates applied.
Network accessibility to MongoDB’s default port 27017 is crucial for client connections. If operating behind firewalls or in cloud environments, configure security groups and firewall rules accordingly.
Pre-installation Checklist
Start by updating your AlmaLinux 10 system to ensure all packages reflect the latest versions:
sudo dnf update -y
Verify your system architecture compatibility, as MongoDB supports x86_64 architecture primarily. Check your system architecture with:
uname -m
Review your firewall configuration and SELinux policies, as these security features may require adjustment for MongoDB operations. Document your current security settings before making modifications to maintain system integrity.
Method 1: Installing MongoDB via Official Repository
The official MongoDB repository provides the most reliable and up-to-date MongoDB packages for AlmaLinux 10. This method ensures you receive official support and timely security updates directly from MongoDB Inc.
System Preparation
Begin by installing the necessary repository management tools:
sudo dnf install -y dnf-plugins-core
These plugins enable advanced repository management features required for adding external repositories securely. The dnf-plugins-core package includes essential utilities for repository configuration and GPG key management.
Verify your system’s package management system is functioning correctly by checking the dnf version:
dnf --version
Adding MongoDB Repository
Create the MongoDB repository configuration file to enable package installation from official sources:
sudo tee /etc/yum.repos.d/mongodb-org-8.0.repo << EOF
[mongodb-org-8.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/\$releasever/mongodb-org/8.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://pgp.mongodb.com/server-8.0.asc
EOF
This configuration establishes a secure connection to MongoDB’s official repository. The GPG key verification ensures package authenticity and prevents tampering during download and installation processes.
Import the MongoDB GPG signing key to verify package integrity:
sudo rpm --import https://pgp.mongodb.com/server-8.0.asc
Verify the repository configuration by listing available MongoDB packages:
dnf list available | grep mongodb-org
This command displays all MongoDB packages available from the newly configured repository, confirming successful repository addition.
MongoDB Installation Process
Install the complete MongoDB package suite using the following command:
sudo dnf install -y mongodb-org
The mongodb-org package includes several essential components:
- mongod: The primary database server daemon
- mongos: The query router for sharded clusters
- mongo shell: Interactive JavaScript interface for database operations
- MongoDB tools: Utilities for backup, restore, and data manipulation
Monitor the installation progress and address any dependency conflicts that may arise. AlmaLinux 10’s package manager automatically resolves most dependencies, but complex environments may require manual intervention.
Verify the installation success by checking the installed MongoDB version:
mongod --version
This command displays the MongoDB server version and build information, confirming successful installation.
Post-Installation Configuration
Enable and start the MongoDB service using systemctl commands:
sudo systemctl enable mongod
sudo systemctl start mongod
Verify the service status to ensure MongoDB runs correctly:
sudo systemctl status mongod
A successful startup displays “active (running)” status with recent log entries indicating database initialization completion.
Method 2: Installing MongoDB via Docker
Docker provides an alternative installation method offering isolation, portability, and simplified deployment management. This approach is particularly valuable for development environments and containerized production deployments.
Docker Installation on AlmaLinux 10
Install Docker Community Edition from the official Docker repository:
sudo dnf install -y yum-utils
sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
sudo dnf install -y docker-ce docker-ce-cli containerd.io
Start and enable the Docker service:
sudo systemctl start docker
sudo systemctl enable docker
Verify Docker installation by checking the version and running a test container:
docker --version
sudo docker run hello-world
Optionally, add your user to the docker group to run Docker commands without sudo:
sudo usermod -aG docker $USER
Log out and back in for group changes to take effect, or use newgrp docker
to activate the group membership immediately.
MongoDB Docker Container Setup
Pull the official MongoDB Docker image from Docker Hub:
docker pull mongo:latest
Create a dedicated directory for MongoDB data persistence:
mkdir -p ~/mongodb/data
This directory ensures data persistence across container restarts and updates. Proper volume management is crucial for production deployments to prevent data loss.
Running MongoDB Container
Launch MongoDB in a Docker container with persistent storage:
docker run -d \
--name mongodb \
-p 27017:27017 \
-v ~/mongodb/data:/data/db \
-e MONGO_INITDB_ROOT_USERNAME=admin \
-e MONGO_INITDB_ROOT_PASSWORD=strongpassword \
mongo:latest
This command creates a MongoDB container with:
- Detached mode operation (-d)
- Named container for easy management
- Port mapping for external access
- Volume mounting for data persistence
- Administrative user creation with authentication
Verify container status and health:
docker ps
docker logs mongodb
Initial MongoDB Configuration
Proper configuration ensures optimal performance and security for your MongoDB deployment.
MongoDB Configuration File
The primary configuration file resides at /etc/mongod.conf
for native installations. This YAML-formatted file controls essential database behavior including network binding, storage options, and security settings.
Key configuration parameters include:
net:
port: 27017
bindIp: 127.0.0.1
storage:
dbPath: /var/lib/mongo
journal:
enabled: true
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
processManagement:
fork: true
pidFilePath: /var/run/mongodb/mongod.pid
Modify these settings based on your specific requirements. For example, change bindIp
to 0.0.0.0
for remote access, though this requires careful security consideration.
Starting MongoDB Service
For native installations, manage MongoDB using systemctl commands:
sudo systemctl start mongod
sudo systemctl enable mongod
sudo systemctl status mongod
The enable command ensures MongoDB starts automatically during system boot, crucial for production environments requiring high availability.
Monitor MongoDB logs for startup messages and potential issues:
sudo tail -f /var/log/mongodb/mongod.log
Successful startup logs display database initialization, index creation, and network binding confirmation.
Firewall Configuration
Configure AlmaLinux 10’s firewall to allow MongoDB connections:
sudo firewall-cmd --permanent --add-port=27017/tcp
sudo firewall-cmd --reload
Verify firewall rule addition:
sudo firewall-cmd --list-ports
For enhanced security, consider restricting access to specific IP addresses or networks:
sudo firewall-cmd --permanent --add-rich-rule="rule family='ipv4' source address='192.168.1.0/24' port protocol='tcp' port='27017' accept"
MongoDB Security Configuration
Security configuration is paramount for MongoDB deployments, especially in production environments.
Enabling Authentication
Create an administrative user before enabling authentication:
mongosh
use admin
db.createUser({
user: "admin",
pwd: "strongpassword123",
roles: [
{ role: "userAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db: "admin" }
]
})
exit
Enable authentication in the MongoDB configuration file by adding:
security:
authorization: enabled
Restart MongoDB to apply authentication settings:
sudo systemctl restart mongod
Test authentication functionality by connecting with credentials:
mongosh -u admin -p strongpassword123 --authenticationDatabase admin
User Management
Create database-specific users with appropriate privileges for application access:
mongosh -u admin -p strongpassword123 --authenticationDatabase admin
use myapplicationdb
db.createUser({
user: "appuser",
pwd: "applicationpassword",
roles: [
{ role: "readWrite", db: "myapplicationdb" }
]
})
Implement role-based access control (RBAC) by creating custom roles tailored to specific application requirements. This approach minimizes security risks by granting only necessary permissions.
Network Security
Bind MongoDB to specific network interfaces to limit exposure:
net:
bindIp: 127.0.0.1,192.168.1.100
For production deployments, implement SSL/TLS encryption by configuring certificates:
net:
ssl:
mode: requireSSL
PEMKeyFile: /etc/ssl/mongodb.pem
CAFile: /etc/ssl/ca.pem
Consider implementing IP whitelisting and network segmentation to further enhance security posture.
Testing and Verification
Thorough testing ensures your MongoDB installation functions correctly and meets performance expectations.
Connection Testing
Test local connections using the MongoDB shell:
mongosh
show databases
db.test.insertOne({message: "Hello MongoDB"})
db.test.find()
These commands verify basic database operations including connection establishment, database listing, document insertion, and retrieval functionality.
For authenticated instances, specify connection parameters:
mongosh mongodb://appuser:applicationpassword@localhost:27017/myapplicationdb
Test remote connections from client applications or other servers to ensure network connectivity and authentication work correctly across your infrastructure.
Performance Verification
Monitor MongoDB performance using built-in diagnostic tools:
mongosh
db.runCommand({serverStatus: 1})
db.stats()
These commands provide comprehensive server statistics including memory usage, connection counts, operation metrics, and storage utilization.
Analyze MongoDB logs for performance warnings or errors:
sudo grep -i "slow" /var/log/mongodb/mongod.log
Implement basic performance benchmarking using MongoDB’s built-in profiler to identify potential bottlenecks in your deployment.
MongoDB Management and Maintenance
Effective management practices ensure long-term reliability and optimal performance.
Basic Operations
Master fundamental MongoDB operations for daily administration:
mongosh
use newdatabase
db.createCollection("users")
db.users.createIndex({email: 1})
show collections
These operations demonstrate database creation, collection management, and index creation for query optimization.
Import and export data using MongoDB tools:
mongoimport --db mydb --collection users --file users.json
mongoexport --db mydb --collection users --out users_backup.json
Backup and Restore
Implement regular backup strategies using mongodump and mongorestore:
mongodump --db myapplicationdb --out /backup/mongodb/$(date +%Y%m%d)
Create automated backup scripts for scheduled execution:
#!/bin/bash
BACKUP_DIR="/backup/mongodb/$(date +%Y%m%d_%H%M%S)"
mongodump --out $BACKUP_DIR
tar -czf $BACKUP_DIR.tar.gz -C /backup/mongodb $(basename $BACKUP_DIR)
rm -rf $BACKUP_DIR
Test backup integrity by performing restore operations in isolated environments before relying on backups for disaster recovery.
Monitoring and Logging
Configure log rotation to manage disk space utilization:
sudo vim /etc/logrotate.d/mongodb
Add log rotation configuration:
/var/log/mongodb/*.log {
daily
missingok
rotate 52
compress
notifempty
sharedscripts
postrotate
/bin/kill -SIGUSR1 $(cat /var/run/mongodb/mongod.pid 2>/dev/null) 2>/dev/null || true
endscript
}
Implement monitoring using MongoDB’s built-in metrics and third-party tools for comprehensive observability.
Troubleshooting Common Issues
Address frequent installation and configuration challenges with proven solutions.
Installation Problems
Repository configuration errors often manifest as package availability issues. Verify repository configuration and GPG key import:
sudo dnf clean all
sudo dnf makecache
GPG key verification failures require manual key import and verification:
rpm -qa | grep gpg-pubkey
sudo rpm --import https://pgp.mongodb.com/server-8.0.asc
Dependency resolution issues may require manual package installation or system update before MongoDB installation.
Service Issues
MongoDB service startup failures often indicate configuration errors or resource constraints. Examine system logs for detailed error messages:
sudo journalctl -u mongod.service -f
Port binding conflicts occur when other services use port 27017. Identify conflicting processes:
sudo netstat -tulpn | grep :27017
sudo lsof -i :27017
SELinux policies may prevent MongoDB operation. Check SELinux status and configure appropriate policies:
getenforce
sudo setsebool -P mongod_can_bind_any_port 1
Connection Problems
Network connectivity issues require systematic troubleshooting. Verify firewall configuration, network routing, and DNS resolution:
telnet localhost 27017
nslookup your-mongodb-server
Authentication failures often result from incorrect credentials or database specification. Verify user permissions and database access rights through direct database queries.
Production Considerations
Production deployments require additional considerations for reliability, performance, and scalability.
Performance Optimization
Optimize memory allocation based on your workload patterns. MongoDB benefits from adequate RAM for in-memory operations and index storage. Configure appropriate cache sizes in the MongoDB configuration:
storage:
wiredTiger:
engineConfig:
cacheSizeGB: 4
Implement strategic indexing to optimize query performance. Analyze query patterns using the MongoDB profiler and create indexes that support your most frequent operations.
Monitor query performance and identify slow operations:
db.setProfilingLevel(2, {slowms: 100})
db.system.profile.find().limit(5).sort({ts: -1}).pretty()
Scaling and High Availability
Plan for horizontal scaling through replica sets for high availability and read scalability:
rs.initiate({
_id: "myReplicaSet",
members: [
{_id: 0, host: "mongodb1.example.com:27017"},
{_id: 1, host: "mongodb2.example.com:27017"},
{_id: 2, host: "mongodb3.example.com:27017"}
]
})
Consider sharding for datasets that exceed single server capacity. Design appropriate shard keys based on query patterns and data distribution requirements.
Implement automated failover and disaster recovery procedures to ensure business continuity during outages or hardware failures.
Alternative Installation Methods
Explore additional installation approaches for specialized requirements.
Installation from Source
Source compilation offers maximum customization and optimization opportunities. Download MongoDB source code and compile with specific flags:
wget https://github.com/mongodb/mongo/archive/r8.0.0.tar.gz
tar -xzf r8.0.0.tar.gz
cd mongo-r8.0.0
python3 buildscripts/scons.py install-mongod --opt=on
Source installation requires extensive build dependencies and compilation time but provides complete control over MongoDB features and optimizations.
Third-party Package Managers
Container orchestration platforms like Kubernetes offer sophisticated MongoDB deployment options through operators and helm charts. These solutions provide automated scaling, backup, and maintenance capabilities for enterprise environments.
Docker Compose simplifies multi-container MongoDB deployments with replica sets and monitoring stack integration:
version: '3.8'
services:
mongodb:
image: mongo:latest
restart: always
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: password
volumes:
- mongodb_data:/data/db
ports:
- "27017:27017"
volumes:
mongodb_data:
Congratulations! You have successfully installed MongoDB. Thanks for using this tutorial for installing MongoDB on your AlmaLinux OS 10 system. For additional help or useful information, we recommend you check the official MongoDB website.