How to remove old and unused Docker images

前端 未结 26 1824
北恋
北恋 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:14

    To remove tagged images which have not container running, you will have to use a little script:

    #!/bin/bash
    
    # remove not running containers
    docker rm $(docker ps -f "status=exited" -q)
    
    declare -A used_images
    
    # collect images which has running container
    for image in $(docker ps | awk 'NR>1 {print $2;}'); do
        id=$(docker inspect --format="{{.Id}}" $image);
        used_images[$id]=$image;
    done
    
    # loop over images, delete those without a container
    for id in $(docker images --no-trunc -q); do
        if [ -z ${used_images[$id]} ]; then
            echo "images is NOT in use: $id"
            docker rmi $id
        else
            echo "images is in use:     ${used_images[$id]}"
        fi
    done
    

提交回复
热议问题