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 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: