Remove All Untagged Docker Images and Stopped Containers

From Bonus Bits
Jump to: navigation, search


This article gives the steps to remove all untagged Docker images and stopped Docker containers. This is useful when building Docker images from Dockerfile files that fail and leave behind broke build containers and unfinished images.

List All Containers

  1. First, we should double check our containers to make sure we're not going to nuke any stopped containers we'd like to keep.
docker ps -a
  1. Second, it's not a bad idea for us to check out what images we have.
docker images

If everything looks acceptable then we can continue with the remove commands.

Remove Stopped Containers

First, we need to remove any stopped containers that may be associated with our untagged images.

docker rm $(docker ps -a -q -f status=exited -f status=dead)
docker ps -a -q -f status=exited -f status=dead | xargs -n1 docker rm

Remove All Untagged Images

Use the following BASH command to remove all of your untagged images. Keep in mind if you built any images and did not tag them then they will be removed as well. You can only remove image if a container is not using it.

docker rmi $(docker images | grep "^<none>" | awk "{print $3}")
docker images | grep '^<none>' | awk '{print $3}' | xargs -n1 docker rmi

Bash Function Example

Here's a quick way to run these commands quickly using a BASH profile funciton. Add this to your bash profile. Such as, $HOME/.bash_profile (if called)

function dnuke() {
    docker ps -a -q -f status=exited -f status=dead | xargs -n1 docker rm
    docker images | grep '^<none>' | awk '{print $3}' | xargs -n1 docker rmi

Related Articles