MongoDB is an open-source NoSQL document database that stores data as flexible BSON documents and scales horizontally through sharding. This guide deploys MongoDB using Docker Compose with persistent volume storage and a root user, then verifies it with the mongosh shell. By the end, you'll have a MongoDB instance ready for application use on your server.
Set Up the Directory Structure
1. Create the project directory structure:
$ mkdir -p ~/mongodb-logging/mongodb-data
$ cd ~/mongodb-logging
2. Create the environment file:
$ nano .env
MONGO_ROOT_USERNAME=admin
MONGO_ROOT_PASSWORD=changeme
Pick a strong password before deploying.
Deploy with Docker Compose
1. Create the Docker Compose manifest:
$ nano docker-compose.yaml
services:
mongodb:
image: mongo:latest
container_name: mongodb
hostname: mongodb
ports:
- "27017:27017"
volumes:
- "./mongodb-data:/data/db"
environment:
- MONGO_INITDB_ROOT_USERNAME=${MONGO_ROOT_USERNAME}
- MONGO_INITDB_ROOT_PASSWORD=${MONGO_ROOT_PASSWORD}
restart: unless-stopped
2. Start the service:
$ docker compose up -d
3. Verify the service is running:
$ docker compose ps
4. View the logs:
$ docker compose logs
Access MongoDB
1. Open a mongosh shell inside the container:
$ docker exec -it mongodb mongosh -u admin -p changeme
2. Switch to an application database and insert a document:
use logs
db.application_logs.insertOne({ level: "info", message: "first entry", timestamp: new Date() })
3. Query and index the collection:
db.application_logs.find()
db.application_logs.createIndex({ timestamp: -1 })
show collections
exit
Next Steps
MongoDB is running with persistent storage and authenticated access. From here you can:
- Create application-scoped users with
db.createUser()instead of using root - Enable TLS by mounting certificates and adding
--tlsMode requireTLS - Bind the port to
127.0.0.1and front MongoDB with a VPN for remote access
For the full guide with additional tips, visit the original article on Vultr Docs.
Top comments (0)