ewilan
ewilan

Reputation: 716

How to remove all associated containers and an image upon Docker build

I'm working on building a Docker image and am wondering if there's a quick way to delete a prior image built from a docker build and remove any previously rendered containers derived from the image during a Docker build.

I know I can do this separately, by removing all containers (running or stopped) associated with an image by using the ancestor filter:

docker rm -f $(docker ps -a -q --filter="ancestor=<image id>")

and I also understand how to remove the associated container:

docker rmi <image id>

However, doing both steps during the next docker build would be ideal.

Upvotes: 8

Views: 5678

Answers (2)

DmitrySemenov
DmitrySemenov

Reputation: 10365

solution

  1. add the following into your ~/.bashrc or ~/.zshrc
  2. source ~/.bashrc (or the file where you put the funcs below)

to delete the image and all associated containers

rem_image 14a7ba8dc2c0

**to delete all images by patterns **

docker_clean <PATTERN>

for example to delete all images having no names (they're usually failed during build step)

docker images | grep none
<none>                                                <none>              e4205cbdcbd6        2 months ago        1.64GB
<none>                                                <none>              e5a21ccf4b6d        2 months ago        1.73GB
<none>                                                <none>              bd9b2ddf1a06        2 months ago        1.64GB
<none>                                                <none>              f7d08c6c4660        2 months ago        1.73GB
<none>                                                <none>              4bca4e8a7059        2 months ago        1.64GB
<none>                                                <none>              ab028586385c        2 months ago        1.73GB

docker_clean none

Code

function rem_image() {
  image_id=$1
  
  docker rm -f $(docker ps -a -q --filter="ancestor=$image_id") 2>&- || echo "Found no containers for that image"
  docker rmi $image_id
  echo "Image deleted successfully"
}

function docker_clean() {
  pattern=$1

  for image_id in `docker images | grep $pattern | awk '{ print $3}'`
  do
      echo Removing... $image_id
      rem_image $image_id
  done
}

Upvotes: 2

VonC
VonC

Reputation: 1328712

However, doing both steps during the next docker build would be ideal.

Scripting those steps would be a simple solution, since docker image build itself does not have those image cleanup option.

And you can add the --no-cache to your docker build, in order to be sure to rebuild everything.

Upvotes: 4

Related Questions