Search code examples
bashdockerdocker-cli

get image ids that not have any running container in docker cli


Is it possible to output the list of image ids that the container is not currently running? This command prints the id list of all the images in the output, but I only want the images that do not have an active container.

docker images -q

Finally, I want to remove the images that do not have an active container delete HDD so that the limited space of the server is not full. Currently, I am using this command docker rmi $(docker images -q), because some of the images have an active container, an error is encountered and the cd job fails. If you know of a bash script that can help, add it.


Solution

  • There is a docker command that deletes images that do not have an associated running container:

    • docker image prune
      allows you to clean up dangling images (a dangling image is not tagged and not referenced by any container)
    • docker image prune -a
      will remove all images that are not used by any existing containers
    • docker image prune -a --filter "until=48h"
      you can add a filter (--filter) to limit the images to be pruned, as in this example, only images that are older than 48 hours

    You can add the -f or --force flag to prune the images and not prompt for confirmation

    You could use this in a scheduled bash script to keep your drive tidy