Docker Container to Backup a MongoDB 5.0 Database with Cron and mongodump in a Docker-Compose setup

Introduction

This Blog-Post describes how to utilize a Docker Container running cron to regularly backup a MongoDB with the Utility-Tool mongodump in a Docker-Compose setup.

Table of Contents

    Use pre-built Docker-Container

    The container used is tarator/mongodump (released on hub.docker.io).

    The file docker-compose.yml might look like this:

    version: '3.1'
    services:
      mongo:
        image: mongo:5.0
        restart: always
        volumes:
          - ./mongo_data:/data/db
    
      mongo-backup:
        image: tarator/mongodump:5.0
        restart: always
        links:
          - mongo
        depends_on:
          - mongo
        volumes:
          - ./mongo_backup:/backup:rw
        environment:
          - MONGO_HOST=mongo
          - MONGO_PORT=27017
          - BACKUP_CRON_TIME=05 18 * * *
          - KEEP_DAYS=14
    

    This creates a Dump of the complete MongoDB everyday at 18:05in the directory ./mongo_backup. The filename of the backup looks like this: mongodump_2021-11-30_18.05.21.gz

    Build Docker-Container from Source

    The sourcecode to the docker-container is released on Gitlab instance: https://gitlab.projecttac.com/tarator/mongodump

    pipeline status

    You can clone and build the container with the following commands:

    git clone https://gitlab.projecttac.com/tarator/mongodump.git
    cd mongodump
    docker build -t myMongodump .

    Restore MongoDB from Zipped Backup

    To restore a backup you can use MongoDB’s utility tool mongorestore. It might look like this, if you’re using the docker-compose file above:

    # Copy backup into the mongo-db directory:
    cp ./mongo_backup/mongodump_2021-11-30_21.35.55.gz ./mongo_data/
    
    # Change into the container
    docker-compose exec mongo bash
    
    # Now you're in the container. Call mongorestore inside
    mongorestore --host localhost:27017 --gzip --archive=/data/db/mongodump_2021-11-30_21.35.55.gz

    Your opinion

    Please let me know in the comments below if this tutorial helped you, to get Monica PRM up and running, or if you’re missing some information which should be added in your opinion.

    2
    0

    Georg Abenthung

    Working in IT since 2004.

    Leave a Reply

    Your email address will not be published. Required fields are marked *