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/
2
Answers
You’re asking:
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
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
).VOLUME
directive.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:Additional references
For more details/remarks about
VOLUME
s, see also:I was having the same issue (newbie) with unnamed / tangling Docker Images and Volumes. After much research and experimentation (and the first answer posted here) I now have a DOCKER-COMPOSE.YAML the can be used to build a generic 3-Tier MERN Stack App that is Dockerized into three Containers. And all the Docker objects are named explicitly by the YAML file.
My 3-TIER MERN App DOCKER-COMPOSE.YAML: