Skip to content

Instantly share code, notes, and snippets.

@ngpestelos
Last active March 5, 2024 20:45
Show Gist options
  • Save ngpestelos/4fc2e31e19f86b9cf10b to your computer and use it in GitHub Desktop.
Save ngpestelos/4fc2e31e19f86b9cf10b to your computer and use it in GitHub Desktop.
How to remove unused Docker containers and images

May 8, 2018

I wrote this four years ago, so instead use this command:

$ docker rmi $(docker images -q -f dangling=true)
@ianmalott
Copy link

As of 1.13.0, see the new prune commands:

docker container prune   # Remove all stopped containers
docker volume prune      # Remove all unused volumes
docker image prune       # Remove unused images
docker system prune      # All of the above, in this order: containers, volumes, images

Bonus:

docker system df         # Show docker disk usage, including space reclaimable by pruning

New Data Management commands PR: moby/moby#26108

@siddharthbarman
Copy link

In Windows using PowerShell, this might work:
&'C:\Program Files\Docker\docker' ps -a | foreach-object { $l = $PSItem.ToString(); $c = $l.Substring(0, $l.IndexOf(" ")); if ($c.ToLower() -ne "container") { $cmd = "c:\Program Files\Docker\docker.exe"; & $cmd "rm" $c } }

@elutsky
Copy link

elutsky commented Jan 4, 2017

Worked great on the Windows container! Thanks!

@dermeister0
Copy link

PowerShell

docker ps -a -q | % { docker rm $_ }
docker images -q | % { docker rmi $_ }

@alexlopes
Copy link

Great gist! Exactly what I was looking for

@rolf-d2i
Copy link

If you dislike shell commands try installing docker for python with for instance pip install docker and use the following script to remove junk images

#!/usr/bin/python

import docker
dockDaemon = docker.from_env()

imgid = [I.id for I in dockDaemon.images.list() if I.attrs["RepoTags"]==[u'<none>:<none>']]

for id in imgid:
   try:
        print "Trying to remove image",id
        dockDaemon.images.remove(id)
        print "Removed image",id
    except docker.errors.APIError,e:
        print "skipping image ",id,"as this is still in use"

@joao-parana
Copy link

@ianmalott list plus:

docker network prune

@yhnu
Copy link

yhnu commented May 10, 2017

mark

@kalakodumuri
Copy link

I am using all those commands. I am getting an error while deleting an image which has dependent containers. I would like to know is there any way of deleting images which does not have any containers associated with it. Because I am running docker rmi command from jenkins job as docker rmi $(docker images -q). This command fails when removing an image which has dependent containers and due to that jenkins job is failing. Any suggestions on this.

@GerBreOwn
Copy link

I have 3 ghost containers that I can't get rid of as they keep reappearing with another ID. I have tried all of the above examples even including one I found in a book which is: "docker update --restart=no <container_id or name>.
Any ideas on how I can make these go away???
Like a T-Shirt I saw "How can I miss you if you won't go away"
Thanks.

@GerBreOwn
Copy link

Finally got rid of those ghosts. Did "docker update --restart=no <container_id or name> or list of containers" and then did a "systemctl restart docker" and then they were gone!!!

@GerBreOwn
Copy link

I lied. 3 minutes after Docker restarted the 3 containers plus 2 more were back.

Does anyone know how I can completely get rid of those unwanted containers???

Thanks.

@88plug
Copy link

88plug commented Jun 21, 2017

@GerBreOwn

docker stop $(docker ps -a -q) &
docker update --restart=no $(docker ps -a -q) &
systemctl restart docker

@jarrekk
Copy link

jarrekk commented Jul 6, 2017

docker image prune

@ronycohen
Copy link

Does anyone know if there is a Windows cheat sheet for all of those commands ?

@rutgerhofste
Copy link

rutgerhofste commented Jul 22, 2017

For Mac OSX I used:

docker rmi `docker images`
docker rm -f `docker ps -a`

Can anybody confirm / improve this command. It seems a bit tricky to me.

@pascalandy
Copy link

On ubuntu 16, I run docker images -q -f dangling=true | xargs --no-run-if-empty docker rmi but I'm getting few error I don't like:

Deleted: sha256:dcb6f5d567c4132f4921475010ac24b363aa69cb553de2a607a3000a5790eb73
Deleted: sha256:55050923de04598352fd3afcd08fb40a363d34528bd88a0b50403ad47eff1818
Untagged: abiosoft/caddy@sha256:9ddf5098c411437eb618f33046b13f2eb2a83e533e582053f0c2d90351b5e29d
Deleted: sha256:81d184abca3c6b789051b123ff5387ce1791b5a3ff363a1190f8bc65cd8ac4d0
Deleted: sha256:7dbeb84197d3d35e83e9d4bbb68e89816a5ed8f62072dc811432da332f4f6373
Deleted: sha256:6fa265aed859e111ca4e83441dce77b14a0692e3c295b72fb84ce696d3f81c4f
Deleted: sha256:ca8067d933cfd402d4f676775f4e623903ba42874fe47cce9694579c08644281
Deleted: sha256:a11b91f29e8caf4313f6f152a31bb63fc3f9ef25184837c4c163f783b4888663
Untagged: gliderlabs/logspout@sha256:9a807db8e9e484920c3228770da76b8af68e8704d8ca0965e68bf8cefc93cee1
Deleted: sha256:87895b8ba6144d395bc439523759a9b5637bf52a1007374fc2c24e1e0eba9067
Deleted: sha256:48f64bfe03edce8015597db7dc32f533538e3b45738af2f086f91ed8510a6299
Deleted: sha256:1e7daedfbf19ac38f824ab39a22c22502a9a6f80fec095b1cd12f37f1ca6b513
Deleted: sha256:e154057080f406372ebecadc0bfb5ff8a7982a0d13823bab1be5b86926c6f860
Error response from daemon: conflict: unable to delete edbfcbd9b2a3 (cannot be forced) - image is being used by running container c505416ead45
Error response from daemon: conflict: unable to delete 9b0dc474ee71 (cannot be forced) - image is being used by running container a0a5bd08a4ba
Error response from daemon: conflict: unable to delete c0daf5d22637 (cannot be forced) - image is being used by running container 6efb59171b5e
Error response from daemon: conflict: unable to delete a7a205723d12 (cannot be forced) - image is being used by running container 82bf86cc7464
Error response from daemon: conflict: unable to delete 47dbf4321bb4 (cannot be forced) - image is being used by running container f1d2bc973e98
Error response from daemon: conflict: unable to delete c68795cb48b2 (cannot be forced) - image is being used by running container 0293120cc87a
Error response from daemon: conflict: unable to delete 08e03914fceb (cannot be forced) - image is being used by running container 74c1e296ff6f

@gnanasundar
Copy link

gnanasundar commented Sep 17, 2017

I had to remove a group of containers with a particular label and the associated images.

This worked for me on windows powershell

docker ps -a -q -f "label=DEV" | foreach-object {docker stop $PSItem.toString()}
docker ps -a -q -f "label=DEV" | foreach-object {$i = docker inspect $PSItem.toString() --format='{{.Config.Image}}'; docker rmi -f $i}
docker ps -a -q -f "label=DEV" | foreach-object {docker rm -f $PSItem.toString()}

For linux:

docker stop $(docker ps -a -q -f "label=DEV")
docker rmi -f $(docker ps -a -q -f "label=DEV" | xargs docker inspect --format='{{.Config.Image}}')
docker rm -f $(docker ps -a -q -f "label=DEV")

@joao-parana
Copy link

I put this alias in my .profile

alias docker-prune='docker system df && docker container prune && docker volume prune && docker system prune && docker system df'

Now, I can run docker-prune to clean-up all my Docker unused resources and reclaim disk space.

@LunaticZorr
Copy link

Stop all containers:
for i in $(docker ps | awk '{print $1}' | awk '{if(NR>1)print}'); do docker stop $i; done

Delete all images:
for i in $(docker images | awk '{print $3}' | awk '{if(NR>1)print}'); do docker rmi $i; done

@friscochap
Copy link

friscochap commented Dec 26, 2017

Remove all docker images marked as "none" in Powershell

docker rmi ((docker images | select-string "<none>" | ConvertFrom-String) | Select -ExpandProperty "P3")

@rpratesh
Copy link

rpratesh commented Feb 27, 2018

This worked for me on Ubuntu 16.04
Before deleting all the containers, force stop them:
docker ps -q -a | xargs docker stop

Then delete the containers using:
docker ps -q -a | xargs docker rm

Now delete all the dangling images using:
docker rmi $(docker images | grep “^<none>” | awk ‘{print $3}’)

@stiv-yakovenko
Copy link

'docker system prune' doesn't remove images on windows

@Barathchander
Copy link

You can try out below script, i am using that below

#!/bin/bash

timestamp=$(date +%Y%m%d_%H%M%S)
log_path="`pwd`"
filename=docker_cleanup_$timestamp.log
log=$log_path/$filename


docker_space_before(){
CURRENTSPACE=`docker system df`
echo "Current Docker Space:" >> $log
echo $CURRENTSPACE >>$log
}
docker_find (){
echo "#####################################################################" >> $log
echo "Finding images" >> $log
echo "#####################################################################" >> $log
REMOVEIMAGES=`docker images | grep " [days|months|weeks]* ago" | awk '{print $3}'`

echo "Listing images that needs to be cleaned up" >> $log
echo $REMOVEIMAGES >>$log

}

docker_cleanup(){
echo "#####################################################################" >> $log
echo "Cleaning images" >> $log
echo "#####################################################################" >> $log
docker rmi ${REMOVEIMAGES}
}

docker_space_after(){
CURRENTSPACE=`docker system df`
echo "Current Docker Space, after clean up:" >> $log
echo $CURRENTSPACE >>$log
}
docker_space_before
docker_find
docker_cleanup
docker_space_after

@jfsdcgy
Copy link

jfsdcgy commented Sep 12, 2018

'docker system prune' doesn't remove images on windows

same here, have you found any solution?

@MagicJohnJang
Copy link

For Windows, what's more:

Stop and remove by image name =>

FOR /f "tokens=*" %i IN ('docker ps -a --filter "ancestor=ImageNameHere" -q') DO docker stop %i && docker rm %i

...

(don't forget to change %i to %%i in batch file)

@RaimundasR
Copy link

RaimundasR commented Mar 17, 2022

the best thing to control and clean up unused containers which still running are to label them on docker run and use few command lines through crontab:
1'st one to kill docker containers creates x time ago and with labe x:
docker ps -a --filter "label=<label_name>" | grep 'x period crated ago' | awk '{ print $1 }' | xargs -I {} docker rm {} -f
2'nd one clean up all unused images which also have tag "none":
docker rmi $(docker images --filter "dangling=true" -q --no-trunc) 2>/dev/null

Then your environment should be always clean :) Cheers....

@Kejk23
Copy link

Kejk23 commented Jul 31, 2022

docker ps -a -q | % { docker rm $_ }
docker images -q | % { docker rmi $_ }

thank you so much

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment