I want to recreate a service, including its volumes. The closest I got was the following commands:
docker-compose stop foo
docker-compose rm -f foo
docker-compose up --renew-anon-volumes -d foo
docker-compose start foo
The issue here is --renew-anon-volumes
recreates all services that have anonymous volumes, not just foo
‘s volumes. If I don’t use --renew-anon-volumes
, then I think I need a named volume to do docker volume rm myvolume
. However, with named volumes, Docker Compose always prepends a project name. Since my script doesn’t know the project name, I can’t programmatically delete the volume. I can’t enforce that the user uses a particular project name. I know I can set the project name using an environment variable, but there’s no guarantee that the user won’t run Docker Compose with a different project name.
I think there are 2 potential solutions:
-
Make
--renew-anon-volumes
only recreate the volumes for the service I specified -
Use a named volume and somehow figure out the correct prefix
Are either of these doable, or is there another solution?
2
Answers
Many roads leading to Rome, depending on your prerequisites:
docker volume ls
and regex the result for your named volume (just working if volume name is unique)external
volumes andvolume create
them with known names by bootstrap script before runningdocker-compose up
(not working if volumes must be instantiated)docker-compose
command (-p NAME
) or by environment variable (COMPOSE_PROJECT_NAME=NAME
).docker-compose -f 'your-down-file.yml' down -v
which removes all named and anonymous volumes belonging to this service anddocker-compose -f .. up
on this file.Edit (@DavidMaze):
You’re right, docker compose recognizes that fact. But it does NOT remove it, just warning. If you want to remove all "orphans" you need the flag
--remove-orphans
.But for some reasons the down does not remove volumes then, even if flag
-v
is given. This could be reported because it is not behaving like described.And errata: the flag
-f
must go before up/down and not after!docker-compose rm
has a-v
option to delete anonymous volumes attached to a container, and also a-s
option to stop the container. For your particular use case it should be enough to:This will only help for anonymous volumes, that is, where the Compose file has
volumes:
with only a container path and there is no corresponding top-levelvolumes:
entry. I don’t immediately see a Compose option to list, remove, or otherwise manage named volumes that Compose created.