Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove anonymous volumes on exit with docker-compose

I have a docker-compose file I use to run integration tests. It's set to --exit-code-from the test service, so when the tests are done all the containers are stopped. There's a database service involved in the test. It creates an anonymous volume. Since these are tests, I don't want to keep the database around between runs. If I was using docker-compose down, I might be able to use -v (the doc says it removes named volumes; maybe it works for anonymous volumes too?). So my question is, how do I tell docker-compose up to delete anonymous volumes on exit?

like image 543
Cully Avatar asked Jan 26 '23 07:01

Cully


1 Answers

The docker-compose up docs have a flag that looks promising:

-V, --renew-anon-volumes   Recreate anonymous volumes instead of retrieving
                           data from the previous containers.

And it turns out that works. If you add the flag, the database is "rebuilt" on each up. I don't think this actually removes the volume on exit. But it does solve the root issue of wanting a fresh instance of the database on each run of the tests.

The final command looks like this:

docker-compose -f docker-compose.test.yml up --renew-anon-volumes --abort-on-container-exit --exit-code-from test

NOTE: The old database container's anonymous volumes are not removed (even on the startup that renews the anon volumes). So you'd have to occasionally remove them (e.g. docker volume prune).

UPDATE (better solution)

Another solution, thanks to @BMitch's comment on the question, is to just run docker-compose down -v after the docker-compose up exits (you can still down the stopped containers because they haven't been removed). This will actually delete the anonymous volume on exit. I'm not sure how you'd do this if you up with -d, but since I'm not using that flag (I want to see the tests run) this command works:

docker-compose -f docker-compose.test.yml up --abort-on-container-exit --exit-code-from test
docker-compose -f docker-compose.test.yml down -v
like image 123
Cully Avatar answered Jan 31 '23 09:01

Cully