Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list images and their containers

Tags:

docker

I am deleting dangling docker images.

Before removing these images, I want to see if there are any containers, which are instances from these dangling images.

If so I want to log them and abort the deletion.

So far I did not find any command for that.

My solution would be to get all containers docker ps -a and all dangling images docker images -aqf dangling=true and compare repo + tag from the image with image from the container.

I am using docker 1.12

like image 331
Hammelkeule Avatar asked Feb 05 '23 09:02

Hammelkeule


1 Answers

How to list images and their containers?

You can edit the --format in order to fit to your needs:

docker ps -a --format="container:{{.ID}} image:{{.Image}}"

How to delete dangling images?

This command is intended to clean dangling image without touching images that are being used by containers:

$ docker image prune

WARNING! This will remove all images without at least one container associated to them.
Are you sure you want to continue? [y/N] y

But if you don't have that command in your docker version, you could try the following.

If the image is dangling, you should see a hash in the IMAGE column in docker ps. That should not be an usual case, tough.

This print the used images by running/stopped containers:

docker ps -a --format="{{.Image}}"

And this list your dangling images:

docker images -qf "dangling=true"

Take with caution:

#!/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"}' \
))

# Remove the unused images
for i in "${DANGLING_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
like image 145
Robert Avatar answered Feb 19 '23 06:02

Robert