[英]How to remove unnamed volumes when docker compose down?
我有一個 docker-compose 文件,它描述了幾個服務。 所有服務都附加了卷,但只有一個服務具有卷的名稱。 當我運行docker compose down
我想自動刪除未命名的卷,同時創建所有丟失的卷。
services:
service1:
image: some/image:1
volumes:
- named-volume:/home/user1
service2:
image: some/image:2
#volumes: not declared volumes that are named automatically with a hash
volumes:
named-volume:
name: volume-for-service1
我第一次運行docker compose up
我想自動創建所有卷(命名和未命名),當我運行docker compose down
我希望刪除未命名的卷,同時保留命名的卷( volume-for-service1
)。 下次我運行docker compose up
它應該只創建未命名的卷,因為命名的卷已經存在。
我努力了:
docker compose down -v
不刪除任何卷docker compose down --remove-orphans
沒有刪除任何卷docker compose down --rmi local
which remove no volumedocker-compose down -v
刪除了命名卷docker-compose down --remove-orphans
沒有刪除任何卷docker-compose down --rmi local
which remove no volume操作系統:Windows 10 x64
我不太明白。 我應該運行什么命令來達到預期的效果?
在啟動服務時嘗試使用--renew-anon-volumes
標志,在關閉服務時使用--volumes
> docker-compose --renew-anon-volumes up
> docker-compose --volumes down
請參閱 docker 撰寫文檔
-V, --renew-anon-volumes Recreate anonymous volumes instead of retrieving
data from the previous containers.
-v, --volumes Remove named volumes declared in the `volumes`
section of the Compose file and anonymous volumes
attached to containers.
為了防止刪除命名卷,您應該在配置文件中將它們定義為外部:
volumes:
volume-for-service1:
name: volume-for-service1
external: true
但是您必須最初在其他地方的配置文件之外創建它們,或者通過:
docker volume create volume-for-service-1
或在單獨的配置文件中。
參考: https://docs.docker.com/compose/compose-file/#external-1
我不知道自動刪除未命名卷的方法,但您可以匹配其 hash 並使用小腳本將其刪除。 要重用您的docker-compose.yml
示例,首先您要獲得給定服務名稱的容器名稱:
docker-compose ps service2 # this is the one with unnamed volume in your example
Output 可能類似於:
NAME COMMAND SERVICE STATUS
project-service2-1 "docker-entrypoint.s…" service2 exited (0)
然后使用容器名稱可以找到它的未命名卷 hash:
docker inspect -f '{{ (index .Mounts 0).Name }}' project-service2-1
現在,在刪除卷之前,您需要關閉容器,否則卷將被使用。
docker-compose down
docker volume rm $volume # replace the "volume" var with the inspect output
既然我們看到了步驟,讓我們試着把它做成一個小腳本(稍微調整一下):
service_name=service2 # set the variable accordingly
container_id=$(docker-compose ps $service_name --quiet)
volume_name=$(docker inspect -f '{{ (index .Mounts 0).Name }}' $container_id)
docker-compose down
docker volume rm -f $volume_name
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.