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.
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/
CodePudding user response:
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…?
- If you're developing your own base image, just avoid using the
VOLUME
directive. - 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 thedocker-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 VOLUME
s, see also:
- the SO question Why do some Docker images have no VOLUME defined? by @s3-89
- this nice blog article by @BMitch