简体   繁体   English

如何使用 docker-compose 在退出时删除匿名卷

[英]How to remove anonymous volumes on exit with docker-compose

I have a docker-compose file I use to run integration tests.我有一个用于运行集成测试的 docker-compose 文件。 It's set to --exit-code-from the test service, so when the tests are done all the containers are stopped.它被设置为--exit-code-from测试服务,所以当测试完成时,所有容器都会停止。 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?).如果我使用docker-compose down ,我可能可以使用-v (文档说它删除了命名卷;也许它也适用于匿名卷?)。 So my question is, how do I tell docker-compose up to delete anonymous volumes on exit?所以我的问题是,我如何告诉docker-compose up在退出时删除匿名卷?

The docker-compose up docs have a flag that looks promising: docker-compose up文档具有一个看上去很有前途的标志:

-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 . 如果添加该标志,则每次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 (eg docker volume prune ). 因此,您有时需要删除它们(例如docker volume prune )。

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). 由于@BMitch对这个问题的评论,另一种解决方案是在docker-compose up退出后仅运行docker-compose down -v (您仍可以按下已停止的容器,因为它们尚未被移除)。 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: 我不确定如果使用-d该怎么做,但是由于我没有使用该标志(我想查看测试在运行),因此此命令有效:

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

你可以跑down-v标志清理卷,如:

docker-compose -f docker-compose.test.yml down -v

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM