How to remove old and unused Docker images

前端 未结 26 1789
北恋
北恋 2020-11-22 11:28

When running Docker for a long time, there are a lot of images in system. How can I remove all unused Docker images at once safety to free up the storage?

In additio

26条回答
  •  礼貌的吻别
    2020-11-22 12:25

    To remove old tagged images that are more than a month old:

    $ docker images --no-trunc --format '{{.ID}} {{.CreatedSince}}' \
        | grep ' months' | awk '{ print $1 }' \
        | xargs --no-run-if-empty docker rmi
    

    Note that it'll fail to remove images that are used by a container, referenced in a repository, has dependent child images... which is probably what you want. Else just add -f flag.

    Example of /etc/cron.daily/docker-gc script:

    #!/bin/sh -e
    
    # Delete all stopped containers (including data-only containers).
    docker ps -a -q --no-trunc --filter "status=exited" | xargs --no-run-if-empty docker rm -v
    
    # Delete all tagged images more than a month old
    # (will fail to remove images still used).
    docker images --no-trunc --format '{{.ID}} {{.CreatedSince}}' | grep ' months' | awk '{ print $1 }' | xargs --no-run-if-empty docker rmi || true
    
    # Delete all 'untagged/dangling' () images
    # Those are used for Docker caching mechanism.
    docker images -q --no-trunc --filter dangling=true | xargs --no-run-if-empty docker rmi
    
    # Delete all dangling volumes.
    docker volume ls -qf dangling=true | xargs --no-run-if-empty docker volume rm
    

提交回复
热议问题