11 MongoDB Management - Jermmyy/IT-Landscape GitHub Wiki

MongoDB Management and Maintenance

Persistent Storage with Docker Volumes

MongoDB stores data inside the container by default, but when the container is removed data disappears. To keep your data safe and persistent, use Docker volumes.

In the docker-compose.yml we have already configured:

volumes:
  mongo-data:

This creates a volume called mongo-data that persists your MongoDB data on the host machine, surviving container restarts and recreation.

You can check your volumes with:

docker volume ls

alt text

And inspect a volume:

docker volume inspect mongo-data

Backing up MongoDB Data

Backing up is essential to prevent data loss.

Backup using mongodump

You can create a backup of your database using mongodump inside the running MongoDB container.

Run this command to create a dump folder on your host machine:

docker exec mongodb mongodump --out /data/backup
docker cp mongodb:/data/backup ./backup

alt text

  • The first command creates a backup inside the container at /data/backup.
  • The second copies it from the container to your local directory ./backup.

Restoring from Backup

To restore a backup, use mongorestore:

docker cp ./backup mongodb:/data/restore
docker exec mongodb mongorestore /data/restore

alt text

This copies your backup folder back into the container and restores the data.


Scaling MongoDB

Simple Scaling with Docker Compose

MongoDB is designed for scalability through repliace sets and sharding. Running these in docker requires more advanced setup (multiple containers, networking).

For basic projects, you can scale your MongoDB container horizontally using Docker Compose:

docker-compose up -d --scale mongodb=3

This command creates 3 instances of the MongoDB container. However, without replica set configuration, these are independent and do not sync data.


Production Ready Scaling

For production, configure MongoDB replica sets with persistent storage per node, and set up networking for replication and failover.


Useful Docker Commands for MongoDB Management

Command Purpose
docker-compose up -d Start containers in detached mode
docker-compose down Stop and remove containers
docker exec -it mongodb mongo Open MongoDB shell inside container
docker logs mongodb View MongoDB container logs
docker volume ls List Docker volumes
docker volume inspect mongo-data Inspect volume details

Useful Links