How to remove old and unused Docker images

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

    I recently wrote a script to solve this on one of my servers:

    #!/bin/bash
    
    # Remove all the dangling images
    DANGLING_IMAGES=$(docker images -qf "dangling=true")
    if [[ -n $DANGLING_IMAGES ]]; then
        docker rmi "$DANGLING_IMAGES"
    fi
    
    # Get all the images currently in use
    USED_IMAGES=($( \
        docker ps -a --format '{{.Image}}' | \
        sort -u | \
        uniq | \
        awk -F ':' '$2{print $1":"$2}!$2{print $1":latest"}' \
    ))
    
    # Get all the images currently available
    ALL_IMAGES=($( \
        docker images --format '{{.Repository}}:{{.Tag}}' | \
        sort -u \
    ))
    
    # Remove the unused images
    for i in "${ALL_IMAGES[@]}"; do
        UNUSED=true
        for j in "${USED_IMAGES[@]}"; do
            if [[ "$i" == "$j" ]]; then
                UNUSED=false
            fi
        done
        if [[ "$UNUSED" == true ]]; then
            docker rmi "$i"
        fi
    done
    

提交回复
热议问题