Sponsored Content

DEV Community

Cover image for Deploying MongoDB NoSQL Document Database on Ubuntu 24.04
Sanskriti Harmukh for Vultr

Posted on with Aashish Chaurasiya Originally published at docs.vultr.com

Deploying MongoDB NoSQL Document Database on Ubuntu 24.04

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
Enter fullscreen mode Exit fullscreen mode

2. Create the environment file:

$ nano .env
Enter fullscreen mode Exit fullscreen mode
MONGO_ROOT_USERNAME=admin
MONGO_ROOT_PASSWORD=changeme
Enter fullscreen mode Exit fullscreen mode

Pick a strong password before deploying.


Deploy with Docker Compose

1. Create the Docker Compose manifest:

$ nano docker-compose.yaml
Enter fullscreen mode Exit fullscreen mode
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
Enter fullscreen mode Exit fullscreen mode

2. Start the service:

$ docker compose up -d
Enter fullscreen mode Exit fullscreen mode

3. Verify the service is running:

$ docker compose ps
Enter fullscreen mode Exit fullscreen mode

4. View the logs:

$ docker compose logs
Enter fullscreen mode Exit fullscreen mode

Access MongoDB

1. Open a mongosh shell inside the container:

$ docker exec -it mongodb mongosh -u admin -p changeme
Enter fullscreen mode Exit fullscreen mode

2. Switch to an application database and insert a document:

use logs
db.application_logs.insertOne({ level: "info", message: "first entry", timestamp: new Date() })
Enter fullscreen mode Exit fullscreen mode

3. Query and index the collection:

db.application_logs.find()
db.application_logs.createIndex({ timestamp: -1 })
show collections
exit
Enter fullscreen mode Exit fullscreen mode

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.1 and 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)