How to persist Mongodb data in containers using Docker volumes

-> Data inside a container is temporary and will be lost once the container stops. Although this may be appropriate for some use cases, ensuring data persistence for databases like MongoDB is crucial.

-> To persist data in a MongoDB container, we use Docker volumes.

-> Docker volumes allow the containers to store data outside of the container filesystem, ensuring data is persistent even after the container is stopped.

-> Create a Docker volume and run the MongoDB container with the volume mounted to ensure data persistence.

    docker volume create mongodb

    docker run --rm -d --name mongodb -v mongodb:/data/db -p 27017:27017 mongo:latest

    -> Log in to the MongoDB container and add sample data.

    docker exec -it mongodb mongosh

    -> Stop the MongoDB container

    docker stop mongodb

    -> Run the MongoDB container, login, and check if the data is still present.

    By Mahesh

    Leave a Reply

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