Search code examples
mongodbdocker-composecontainersdocker-volume

Default volumes created while running mongodb images


I am trying to run mongodb using docker-compose. Every time I restart the containers, I see that mongo creates default volumes with random names and the number of volume grows.

enter image description here

Why these volumes are created and how can I avoid them.

My docker-compose.yml for mongo is as follows:

mongo:
    image: mongo
    restart: always
    networks:
      - ts-net
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: root
    volumes:
      - db_data:/data/db/

Solution

  • You're asking:

    Why these volumes are created…?

    The volumes you speak about are called anonymous volumes. They can typically be created by the Dockerfile directive VOLUME, e.g.:

    github.com/docker-library/mongo/blob/master/5.0/Dockerfile

    VOLUME /data/db /data/configdb
    

    These volumes have indeed the drawbacks that (i) their automatically-generated name does not refer to the image they were created from, and that (ii) they are not removed once the corresponding container is removed (unless we use the CLI option docker run --rm).

    how can I avoid them…?

    1. If you're developing your own base image, just avoid using the VOLUME directive.
    2. Otherwise, the best way to cope with existing images relying on the VOLUME directive is to (i) figure out which paths are associated to a given volume, and (ii) associate these paths to a named volume within the docker-compose.yml specification, namely:
    services:
    
      db:
        image: mongo:5.0
        restart: always
        environment:
          MONGO_INITDB_ROOT_USERNAME: root
          MONGO_INITDB_ROOT_PASSWORD: root
        volumes:
          - 'db_data:/data/db'
          - 'db_config:/data/configdb'
        networks:
          - db-net
    
    networks:
      db-net:
        driver: bridge
    
    volumes:
      db_data:
        driver: local
      db_config:
        driver: local
    

    Additional references

    For more details/remarks about VOLUMEs, see also: