Home > Net >  docker-compose how to persist mongodb-database
docker-compose how to persist mongodb-database

Time:10-16

I am using docker-compose and here is my docker-compose.yaml file:

version: "3.7"
services:
  node:
    container_name: my-app
    image: my-app
    build:
      context: ./my-app-directoty
      dockerfile: Dockerfile
    command: npm run dev
    environment:
      MONGO_URL: my-database
      port: 3000
    volumes:
      - ./my-app-directory/src:/app/src
      - ./my-app-directory/node_modules:/app/node_modules
    ports:
      - "3000:3000"
    networks:
      - my-app-network
    depends_on:
      - my-database

  my-database:
    container_name: my-database
    image: mongo
    ports:
      - "27017:27017"
    networks:
      - my-app-network

networks:
  my-app-network:
    driver: bridge

I expect to find a clear and newly created database each time I run the following command:

docker-compose build
docker-compose up

But this is not the case. When I bring the containers up with docker-compose up, my database has the exact state of the last time I shut it down with docker-compose down command. And since I have not specified a volume prop in my-database object, is this normal behaviour? Does this mean that no other action to persisting database state is required? And can I use this in production if I ever choose to use docker-compose?

CodePudding user response:

The mongo image define the following volumes:

  • /data/configdb
  • /data/db

So docker-volume will create and use a unamed volume for data/db.

If you want to have a new one, use:

docker-compose down -v
docker-compose up -d --build

Or use a mount point mounted on the volume location like:

volumes:
  - ./db:/data/db:rw

And drop your local db directories when you want to start over.

  • Related