Search code examples
mongodbdockerdocker-composecontainers

How to completely destroy Mongo database created by docker-compose?


I am using docker-compose to create a MongoDB service. Here is how it looks:

services:
  database:
    image: 'mongo'
    environment: 
      - MONGO_DATA_DIR=/data/db
      - MONGO_INITDB_DATABASE=azunyan
    volumes:
      - ./container-scripts/mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js
      - ./data/db:/data/db

I build and run the service using sudo docker-compose up --build -d database and this creates the MongoDB container.

During testing I add a few collections to the database by connecting to the database through mongo <container ip address> and issuing a few mongo commands (e.g. db.createCollection())

Afterwards, I use sudo docker-compose down -v to remove the container, and I also run sudo docker system prune -a -f just to be sure. I expect that the next time I build and run the image, the database should be empty (i.e. have no collections), however I can see the collections are still there. Why? How do I get a clean MongoDB container?


Solution

  • You need to delete your data directory and then destroy and recreate your database container.

    docker-compose down
    rm -rf ./data/db
    docker-compose up -d database
    

    Note: You do not need the --build flag as you are referencing a pre-build image in your docker-compose file. You also don't need to specify the database service unless you have other entries within your compose file that you didn't add to the example. You also don't need docker system prune.