How does one remove a Docker image? - docker

I'm running Docker under Vagrant under OS X 10.8.4 (Mountain Lion), and whenever I try to delete a saved image, I get an error:
$ docker rmi some-image-id
2013/07/15 hh:mm:ss unexpected JSON input
According to the rmi help, the proper syntax is docker rmi IMAGE [IMAGE...], and I'm not sure what to make of that.
How can I delete an image?
$ docker version
Client version: 0.4.8
Server version: 0.4.8
Go version: go1.1
 
$docker info
Containers: 1
Images: 3
Interestingly, when I run docker ps, no containers show up at all. Running docker images shows four (4) base images and one (1) node image.

Try docker rmi node. That should work.
Seeing all created containers is as simple as docker ps -a.
To remove all existing containers (not images!) run docker rm $(docker ps -aq)

The following are some of the ways to remove docker images/containers:
Remove single image
docker rmi image_name:version/image-id
Remove all images
docker rmi $(docker images -qf "dangling=true")
Kill containers and remove them:
docker rm $(docker kill $(docker ps -aq))
Note: Replace kill with stop for graceful shutdown
Remove all images except "my-image"
Use grep to remove all except my-image and ubuntu
docker rmi $(docker images | grep -v 'ubuntu\|my-image' | awk {'print $3'})
Or (without awk)
docker rmi $(docker images --quiet | grep -v $(docker images --quiet ubuntu:my-image))

Delete all docker containers
docker rm $(docker ps -a -q)
Delete all docker images
docker rmi $(docker images -q)

To remove an image from Docker using the image ID:
Get the list of all Images
docker images
Identify the image ID of the image you want to delete, for example:
REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE
kweku360/java latest 08d3a9b8e166 2 weeks ago 5.733 GB`
Finally remove the image using the image ID (only the first three digits are required)
docker rmi 08d

Image:
List images
docker images
Remove one image
docker rmi image_name
Force remove one image
docker rmi -f image_name
Container:
List all containers
docker ps -a
Remove one container
docker rm container_id
Force remove one container
docker rm -f container_id

Update, as commented by VonC in How to remove old Docker containers.
With Docker 1.13 (Q4 2016), you now have:
docker system prune will delete ALL unused data (i.e., in order: containers stopped, volumes without containers and images with no containers).
See PR 26108 and commit 86de7c0, which are introducing a few new commands to help facilitate visualizing how much space the Docker daemon data is taking on disk and allowing for easily cleaning up "unneeded" excess.
docker system prune
WARNING! This will remove:
- all stopped containers
- all volumes not used by at least one container
- all images without at least one container associated to them
Are you sure you want to continue? [y/N] y

Removing Containers
To remove a specific container
docker rm CONTAINER_ID CONTAINER_ID
For single image
docker rm 70c0e19168cf
For multiple images
docker rm 70c0e19168cf c2ce80b62174
Remove exited containers
docker ps -a -f status=exited
Remove all the containers
docker ps -q -a | xargs docker rm
Removing Images
docker rmi IMAGE_ID
Remove specific images
for single image
docker rmi ubuntu
for multiple images
docker rmi ubuntu alpine
Remove dangling images
Dangling images are layers that have no relationship to any tagged images as the Docker images are constituted of multiple images.
docker rmi -f $(docker images -f dangling=true -q)
Remove all Docker images
docker rmi -f $(docker images -a -q)
Removing Volumes
To list volumes, run docker volume ls
Remove a specific volume
docker volume rm VOLUME_NAME
Remove dangling volumes
docker volume rm $(docker volume ls -f dangling=true -q)
Remove a container and its volumes
docker rm -v CONTAINER_NAME

docker rm container_name
docker rmi image_name
docker help
rm Remove one or more containers
rmi Remove one or more images

docker rmi 91c95931e552
Error response from daemon: Conflict, cannot delete 91c95931e552 because the container 76068d66b290 is using it, use -f to force
FATA[0000] Error: failed to remove one or more images
Find container ID,
# docker ps -a
# docker rm daf644660736

First of all, we have to stop and remove the Docker containers which are attached with the Docker image that we are going to remove.
So for that, first
docker stop container-id - To stop the running container
docker rm container-id - To delete/remove the container
then,
docker rmi image-id - To delete/remove the image

For versions 1.13 and higher:
docker image rm [OPTIONS] IMAGE [IMAGE...]
Comparing:
the documention of docker image rm and
the documentation of docker rmi,
the [OPTIONS] seem to have no difference.
--force , -f Force removal of the image
--no-prune Do not delete untagged parents
From: Introducing Docker 1.13
CLI restructured
In Docker 1.13, we regrouped every command to sit under the logical object it’s interacting with. For example list and start of containers are now subcommands of docker container and history is a subcommand of docker image.
These changes let us clean up the Docker CLI syntax, improve help text and make Docker simpler to use. The old command syntax is still supported, but we encourage everybody to adopt the new syntax.

Docker provides some command to remove images.
Show/Remove Images:
docker images
docker images -a # All images
docker images --no-trunc # List the full length image IDs
docker images --filter "dangling=true" // Show unstage images
docker rmi $(docker images -f "dangling=true" -q) # Remove on unstages images
docker rmi <REPOSITORY> or <Image ID> # Remove a single image
docker image prune # Interactively remove dangling images
docker image prune -a # Remove all images
or
docker rmi -f $(sudo docker images -a -q)
Also, you can also use filter parameters to remove set of images at
once:
Example:
$docker images --filter "before=<hello-world>" // It will all images before hello-world
$docker images --filter "since=<hello-world>" // It will all images since hello-world
So you can delete that filter images like this:
docker rmi $(docker images --filter "since=<hello-world>")
docker rmi $(docker images --filter "before=<hello-world>")

Delete all of them using
Step 1: Kill all containers
for i in `sudo docker ps -a | awk '{ print $1 }'`; do sudo docker kill $i ; done
Step 2: RM them first
for i in `sudo docker ps -a | awk '{ print $1 }'`; do sudo docker rm $i ; done
Step 3: Delete the images using force
for i in `sudo docker images | awk '{ print $3}'`; do sudo docker rmi --force $i ; done
Use the step 1 in case you are getting error saying it cant be deleted owing to child dependencies

If you want to automatically/periodically clean up exited containers and remove images and volumes that aren't in use by a running container you can download the image meltwater/docker-cleanup.
I use this on production since we deploy several times a day on multiple servers, and I don't want to go to every server to clean up (that would be a pain).
Just run:
docker run -d -v /var/run/docker.sock:/var/run/docker.sock:rw -v /var/lib/docker:/var/lib/docker:rw --restart=unless-stopped meltwater/docker-cleanup:latest
It will run every 30 minutes (or however long you set it using DELAY_TIME=1800 option) and clean up exited containers and images.
More details: https://github.com/meltwater/docker-cleanup/blob/master/README.md

Here's a shell script to remove a tagged (named) image and it's containers.
Save as docker-rmi and run using 'docker-rmi my-image-name'
#!/bin/bash
IMAGE=$1
if [ "$IMAGE" == "" ] ; then
echo "Missing image argument"
exit 2
fi
docker ps -qa -f "ancestor=$IMAGE" | xargs docker rm
docker rmi $IMAGE

In my case the probleme is that I have tow images withe same name
the solution is to add the tag after the name or the id
sudo docker rmi <NAME>:<TAG>
ex:
sudo docker rmi php:7.0.4-fpm

Why nobody mentioned docker-compose! I 've just been using it for one week, and I cannot survive without it. All you need is writing a yml which takes only several minutes of studying, and then you are ready to go. It can boot images, containers (which are needed in so-called services) and let you review logs just like you use with docker native commands. Git it a try:
docker-compose up -d
docker-compose down --rmi 'local'
Before I used docker-compose, I wrote my own shell script, then I had to customize the script whenever needed especially when application architecture changed. Now I don't have to do this anymore, thanks to docker-compose.

For me the following worked fine:
> docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
debian jessie 86baf4e8cde9 3 weeks ago 123MB
ubuntu yakkety 7d3f705d307c 3 weeks ago 107MB
alpine 3.5 074d602a59d7 7 weeks ago 3.99MB
Then go ahead and remove an image by running some like these:
> docker rmi debian:jessie
> docker rmi ubuntu:yakkety
> docker rmi alipine:3.5

List images:
ahanjura#ubuntu:~$ sudo docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
88282f8eda00 19 seconds ago 308.5 MB
13e5d3d682f4 19 hours ago 663 MB
busybox2 latest 05fe66bb1144 20 hours ago 1.129 MB
ubuntu 16.04 00fd29ccc6f1 5 days ago 110.5 MB
ubuntu 14.04 67759a80360c 5 days ago 221.4 MB
python 2.7 9e92c8430ba0 7 days ago 680.7 MB
busybox latest 6ad733544a63 6 weeks ago 1.129 MB
ubuntu 16.10 7d3f705d307c 5 months ago 106.7 MB
Delete images:
ahanjura#ubuntu:~$ sudo docker rmi 88282f8eda00
Deleted: sha256:88282f8eda0036f85b5652c44d158308c6f86895ef1345dfa788318e6ba31194
Deleted: sha256:4f211a991fb392cd794bc9ad8833149cd9400c5955958c4017b1e2dc415e25e9
Deleted: sha256:8cc6917ac7f0dcb74969ae7958fe80b4a4ea7b3223fc888dfe1aef42f43df6f8
Deleted: sha256:b74a8932cff5e61c3fd2cc39de3c0989bdfd5c2e5f72b8f99f2807595f8ece43
ahanjura#ubuntu:~$ sudo docker rmi 13e5d3d682f4
Error response from daemon: conflict: unable to delete 13e5d3d682f4 (must be forced) - image is being used by stopped container 5593e25eb638
Delete by force:
ahanjura#ubuntu:~$ sudo docker rmi -f 13e5d3d682f4
Deleted: sha256:13e5d3d682f4de973780b35a3393c46eb314ef3db45d3ae83baf2dd9d702747e
Deleted: sha256:3ad9381c7041c03768ccd855ec86caa6bc0244223f10b0465c4898bdb21dc378
Deleted: sha256:5ccb917bce7bc8d3748eccf677d7b60dd101ed3e7fd2aedebd521735276606af
Deleted: sha256:18356d19b91f0abcc04496729c9a4c49e695dbfe3f0bb1c595f30a7d4d264ebf

First list all your images which are present by using :
docker images
For removing single image
Use docker rmi [image-name (or) image-id]
// This will remove only that specific image
For removing All images
Use docker rmi -f $(docker images -a -q)

Related

Not being able to remove docker images with "docker image prune -a"

I have two docker images that I would like to remove, but it seems that they cannot be removed with docker image prune -a. Why? The two images are not used in the terminal, since I just restarted the terminal.
(base) ~ % docker image ls
REPOSITORY TAG IMAGE ID CREATED SIZE
test_docker latest 245e34778213 10 minutes ago 1.34GB
<none> <none> 02f2aa7b08bb 41 minutes ago 1.21GB
(base) ~ % docker image prune -a
WARNING! This will remove all images without at least one container associated to them.
Are you sure you want to continue? [y/N] y
Total reclaimed space: 0B
How can I remove the images?
You'll need to make sure all Docker containers are stopped and removed, after that you can remove the Docker images.
Stop and remove all docker containers and images:
List all containers (only IDs) docker ps -aq.
Stop all running containers. docker stop $(docker ps -aq)
Remove all containers. docker rm $(docker ps -aq)
Remove all images. docker rmi $(docker images -q)
or docker image prune -a
docker image prune only remove images not currently associated with a container.
You may want to use docker rmi [image id] (example docker rmi 245e34778213) instead.

Docker rmi - Is it okay to use --force?

I am rather new to Docker, I have recently started running ubuntu container, and stopped it gracefully a few days later (I do not see it using "docker ps"). When I tried to remove ubuntu image using
docker rmi ubuntu
I got the following error:
Error response from daemon: conflict: unable to remove repository reference "ubuntu" (must force) - container 65c315b169b8 is using its referenced image 747cb2d
60bbe
Can I use "--force" to force a removal of the image,
docker rmi ubuntu --force
Or is there a graceful/safer way to do it?
By default docker ps will only show running containers. You can show the stopped ones using docker ps --all.
You can then remove the container first with docker rm <CONTAINER_ID>
If you want to remove all of the containers, stopped or not, you can achieve this from a bash prompt with
$ docker rm $(docker ps --all -q)
The -q switch returns only the IDs
Since everyone else seemed unwilling to test yet willing to preach, I decided to test this out myself:
I downloaded a new image so I knew it wasn't in use
I ran a new container
I deleted the image using docker rmi --force <name>
Image was only untagged, not deleted
I failed to delete the image using docker rmi --force <ID> as docker rebuked with "image is being used by running container 922a12161de6"
So the results are:
The image gets untagged when you name it, but Docker (at least the version I'm using, 19.03.5 build 633a0ea) is smart enough to not actually delete the layers when they are in use.
As a result, the container continues to run fine as the layers are still there, they're simply untagged. You can docker rmi <ID> or docker images prune (without -a it will only delete "dangling" images, I. E. not including unused ones).
Thus the answer is "yes, but it won't delete containers if that's what you're hoping for", but now you know why.
I'm not satisfied with how most of the other answers tell you to find running containers, however, since they seem to say "list all images" -- why? You're trying to delete a specific image.
Stefano's answer is more accurate but here are some tweaks to it:
imageName=ubuntu
containerIds=$(docker ps -a | grep "$imageName" | awk '{ print $1 }')
docker stop $containerIds
docker rm $containerIds
docker rmi "$imageName"
Basically, I added a variable for the image naem and a stop step.
Docker doesn't copy the image data to each container, all the containers running the image have a read only pointer to that part of the filesystem (with their own local RW layer for the individual containers). So if you delete an image while a container is using it, you would break the container and overlay filesystem that it depends on.
Instead, just remove the container first. It may be exited rather than running, so you can do a docker ps -a | grep $image_id for a quick list of containers running that specific image id, but the preferred list would include any descendants:
docker rm $(docker ps -aq --filter "ancestor=747cb2d60bbe")
Then you'll be able to run your docker image rm (or docker rmi) command.
Update: If you force remove an image, all docker does is untag it. The image layers still exists on the filesystem until the container is deleted and then you can delete those image layers. E.g.:
/ $ docker run -d --rm busybox tail -f /dev/null
dac68c445371feab453ba3e3fc80efee52043f6b177fd0a71d0b55b38753f2cf
/ $ docker image rm busybox
Error response from daemon: conflict: unable to remove repository reference "busybox" (must force) - container dac68c445371 is using its referenced image 020584afccce
/ $ docker image rm --force busybox
Untagged: busybox:latest
Untagged: busybox#sha256:1303dbf110c57f3edf68d9f5a16c082ec06c4cf7604831669faf2c712260b5a0
/ $ docker image ls -a
REPOSITORY TAG IMAGE ID CREATED SIZE
<none> <none> 020584afccce 2 weeks ago 1.22MB
Even after deleting the container the layers are still there:
/ $ docker ps -l
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
dac68c445371 020584afccce "tail -f /dev/null" 52 seconds ago Up 50 seconds brave_yalow
/ $ docker stop dac
dac
/ $ docker image ls -a
REPOSITORY TAG IMAGE ID CREATED SIZE
<none> <none> 020584afccce 2 weeks ago 1.22MB
But after the container has been removed you can cleanup the layers:
/ $ docker image prune
WARNING! This will remove all dangling images.
Are you sure you want to continue? [y/N] y
Deleted Images:
deleted: sha256:020584afccce44678ec82676db80f68d50ea5c766b6e9d9601f7b5fc86dfb96d
deleted: sha256:1da8e4c8d30765bea127dc2f11a17bc723b59480f4ab5292edb00eb8eb1d96b1
Total reclaimed space: 1.22MB
If you want to do it gracefully, you should find if there are other images using ubuntu. Anyway in your case, you have a container related to that image.
Here's an example script on how to get this:
containerId=$( docker container ls -a | grep ubuntu | awk '{ print $1 }' )
docker container rm $containerId
docker image rm ubuntu
Remove all containers and after all images to win some space !
$ docker rm $(docker ps -all -q)
$ docker rmi $(docker image ls -q)
You can try the prune option available with docker images in case you want to remove all unused images.
https://docs.docker.com/engine/reference/commandline/image_prune/#usage
docker image prune -a
When would one delete docker images
When they are short of disk space and
They know for certain that they dont need an image or if they can readily download from internet/docker registry later when they need
So if you have internet access and if you have disk space issues you can just delete the image by force
Why you are getting the error:
Docker thinks there is a container - which is currently stopped - which was using this image. If you delete this stopped docker, "docker rmi" would work without force
These are the basic useful commands for docker to view and delete stuff.
View all docker images: docker image ls
View docker containers: docker ps
Stop docker container: docker stop <container name>
Remove docker container: docker rm <container name>
Remove docker image: docker rmi image <image name>
Delete Docker images except for current one - docker image prune -a

Can’t delete docker image with dependent child images

I am trying
docker rmi c565603bc87f
Error:
Error response from daemon: conflict: unable to delete c565603bc87f
(cannot be forced) - image has dependent child images
So i can't delete image even with -f flag. How to delete image then and all of its children ?
Linux and docker version:
uname -a
Linux goracio-pc 4.4.0-24-generic #43-Ubuntu SMP Wed Jun 8 19:27:37 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
docker version
Client:
Version: 1.11.2
API version: 1.23
Go version: go1.5.4
Git commit: b9f10c9
Built: Wed Jun 1 22:00:43 2016
OS/Arch: linux/amd64
Server:
Version: 1.11.2
API version: 1.23
Go version: go1.5.4
Git commit: b9f10c9
Built: Wed Jun 1 22:00:43 2016
OS/Arch: linux/amd64
In some cases (like in my case) you may be trying to delete an image by specifying the image id that has multiple tags that you don't realize exist, some of which may be used by other images. In which case, you may not want to remove the image.
If you have a case of redundant tags as described here, instead of docker rmi <image_id> use docker rmi <repo:tag> on the redundant tag you wish to remove.
You should try to remove unnecessary images before removing the image:
docker rmi $(docker images --filter "dangling=true" -q --no-trunc)
After that, run:
docker rmi c565603bc87f
all previous answers are correct but here is one solution which is just deleteing all of your images forcefully (use this command at your own risk it will delete all of your images)
docker rmi $(docker images -q) -f
find the image id and parent id for all image created after the image in question with the following:
docker inspect --format='{{.Id}} {{.Parent}}' $(docker images --filter since=<image_id> -q)
Then you call command:
docker rmi {sub_image_id}
"sub_image_id" is ID of dependent image
What worked to me was to use the REPOSITORY:TAG combination rather than IMAGE ID.
When I tried to delete a docker image with the command docker rmi <IMAGE ID> with no containers associated with this image I had the message:
$ docker rmi 3f66bec2c6bf
Error response from daemon: conflict: unable to delete 3f66bec2c6bf (cannot be forced) - image has dependent child images
I could delete with success when I used the command docker rmi RPOSITORY:TAG
$ docker rmi ubuntu:18.04v1
Untagged: ubuntu:18.04v1
THIS COMMAND REMOVES ALL IMAGES (USE WITH CAUTION)
Have you tried to use --force
sudo docker rmi $(sudo docker images -aq) --force
This above code run like a charm even doe i had the same issue
If you want to Untag Docker Images
docker rmi <rep:tag>
If you want to Removing Docker Images
docker image rm <image_id>
Ex: Type docker image ls to show info of Images
REPOSITORY TAG IMAGE ID CREATED SIZE
python 3.6 60f85556d5d2 4 days ago 174MB
docker rmi python:3.6
docker image rm 60f85556d5d2
The answer here is to find all descendent children, which has an answer here:
docker how can I get the list of dependent child images?
Then use that to remove the child images in order.
Here's a script to remove an image and all the images that depend on it.
#!/bin/bash
if [[ $# -lt 1 ]]; then
echo must supply image to remove;
exit 1;
fi;
get_image_children ()
{
ret=()
for i in $(docker image ls -a --no-trunc -q); do
#>&2 echo processing image "$i";
#>&2 echo parent is $(docker image inspect --format '{{.Parent}}' "$i")
if [[ "$(docker image inspect --format '{{.Parent}}' "$i")" == "$1" ]]; then
ret+=("$i");
fi;
done;
echo "${ret[#]}";
}
realid=$(docker image inspect --format '{{.Id}}' "$1")
if [[ -z "$realid" ]]; then
echo "$1 is not a valid image.";
exit 2;
fi;
images_to_remove=("$realid");
images_to_process=("$realid");
while [[ "${#images_to_process[#]}" -gt 0 ]]; do
children_to_process=();
for i in "${!images_to_process[#]}"; do
children=$(get_image_children "${images_to_process[$i]}");
if [[ ! -z "$children" ]]; then
# allow word splitting on the children.
children_to_process+=($children);
fi;
done;
if [[ "${#children_to_process[#]}" -gt 0 ]]; then
images_to_process=("${children_to_process[#]}");
images_to_remove+=("${children_to_process[#]}");
else
#no images have any children. We're done creating the graph.
break;
fi;
done;
echo images_to_remove = "$(printf %s\n "${images_to_remove[#]}")";
indices=(${!images_to_remove[#]});
for ((i="${#indices[#]}" - 1; i >= 0; --i)) ; do
image_to_remove="${images_to_remove[indices[i]]}"
if [[ "${image_to_remove:0:7}" == "sha256:" ]]; then
image_to_remove="${image_to_remove:7}";
fi
echo removing image "$image_to_remove";
docker rmi "$image_to_remove";
done
Trying to delete image id : b721d1cdaac7
docker rmi b721d1cdaac7 -f
Response : Error response from daemon: conflict: unable to delete b721d1cdaac7 (cannot be forced) - image has dependent child images
To delete all child images command :
docker image rm $(docker images --filter since=b721d1cdaac7 -q) -f
It will first untagged and removed all child images
# docker rm $(docker ps -aq)
After that use the command as Nguyen suggested.
Building on Simon Brady's brute force method here, if you don't have a ton of images you can use this shell function:
recursive_remove_image() {
for image in $(docker images --quiet --filter "since=${1}")
do
if [ $(docker history --quiet ${image} | grep ${1}) ]
then
recursive_remove_image "${image}"
fi
done
echo "Removing: ${1}"
docker rmi -f ${1}
}
and then call it using recursive_remove_image <image-id>.
Please run this docker command
docker image rm -f $(docker image ls --filter dangling=true -q)
and then run
docker image rm -f $(docker image ls -a -q)
I found the above commands very helpful after working for many hours.
Otherwise, you can run prune script.
https://gist.github.com/sethbergman/cb0f1f700b1f6474b9738191055c9fb7
When i want to remove some unused image with name "<none>" in docker i face with the problem unable to delete a354bbc7c9b7 (cannot be forced) - image has dependent child images.So for solving this problem:
sudo docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
01ee1276bbe0 lizard:1 "/bin/sh -c 'java ..." About an hour ago Exited (1) About an hour ago objective_lewin
49d73d8fb023 javaapp:latest "/usr/bin/java -ja..." 19 hours ago Up 19 hours 0.0.0.0:8091->8091/tcp pedantic_bell
405fd452c788 javaapp:latest "/usr/bin/java -ja..." 19 hours ago Created infallible_varahamihira
532257a8b705 javaapp:latest "/usr/bin/java -ja..." 19 hours ago Created demo-default
9807158b3fd5 javaapp:latest "/usr/bin/java -ja..." 19 hours ago Created xenodochial_kilby
474930241afa jenkins "/bin/tini -- /usr..." 13 days ago Up 4 days 0.0.0.0:8080->8080/tcp, 0.0.0.0:50000->50000/tcp myjenkins
563d8c34682f mysql/mysql-server:latest "/entrypoint.sh my..." 3 weeks ago Up 4 days (healthy) 0.0.0.0:3306->3306/tcp, 33060/tcp mymysql
b4ca73d45d20 phpmyadmin/phpmyadmin "/run.sh phpmyadmin" 4 weeks ago Exited (0) 3 weeks ago phpmyadmin
you can see that i have several Images with name javaapp:latest and different container name. So, i killed and remove all container of "javaapp:latest" container with:
sudo docker stop "containerName"
sudo docker rm "containrName"
Then
sudo docker rmi -f "imageId"
So i can remove all the images with name "<none>"
goodluck
As explained here, I used the following way to identify dependent images and delete them,
image_id=123456789012
docker images -a -q --filter since=$image_id |
xargs docker inspect --format='{{.Id}} {{.Parent}}'
You would see something similar to this as the output:
sha256:f7ef19862215ec0bf7a6b103504d213e1c001691703808f4154689cfbb5f14f9 sha256:a7d2efad2847bd10e5223980ed80f5781c716eddbf6131a3cf97614e7f2db97f
sha256:03690ae141346203959d0ae1b3e8d34b7a4232095d774af57dda6282fce99cc4 sha256:5713074659bb5352496ea680a903eba2f66e0495538c9db37336f4ba92994ea8
sha256:311f587811942d328edc52e5953d794eb9b81fe392512080d9fc1d350a6b2024 sha256:aa674f7f2621946db257720c378377b8714739d20879542d875b84c53b59bc75
Then you can delete those images one by one as below:
docker image rm f7ef19862215ec0bf7a6b103504d213e1c001691703808f4154689cfbb5f14f9
Output something similar to bellow:
Untagged: prathap/cognitive_robotics_gpu:v1
Untagged: prathap/cognitive_robotics_gpu#sha256:db6e7543a13e9a96241c985b9b3145b8fd65effb68c183301385b495875f1a5a
Deleted: sha256:03690ae141346203959d0ae1b3e8d34b7a4232095d774af57dda6282fce99cc4
Deleted: sha256:263f655670436758f8e3f23f31170083fc8d60c4eebe01a5b3fda1e73bed3ad1
Expanding on the answer provided by #Nguyen - this function can be added to your .bashrc etc and then called from the commandline to help clean up any image has dependent child images errors...
You can run the function as yourself, and if a docker ps fails, then it will run the docker command with sudo and prompt you for your password.
Does NOT delete images for any running containers!
docker_rmi_dependants ()
{
DOCKER=docker
[ docker ps >/dev/null 2>&1 ] || DOCKER="sudo docker"
echo "Docker: ${DOCKER}"
for n in $(${DOCKER} images | awk '$2 == "<none>" {print $3}');
do
echo "ImageID: $n";
${DOCKER} inspect --format='{{.Id}} {{.Parent}}' $(${DOCKER} images --filter since=$n -q);
done;
${DOCKER} rmi $(${DOCKER} images | awk '$2 == "<none>" {print $3}')
}
I also have this in my .bashrc file...
docker_rm_dangling ()
{
DOCKER=docker
[ docker ps >/dev/null 2>&1 ] || DOCKER="sudo docker"
echo "Docker: ${DOCKER}"
${DOCKER} images -f dangling=true 2>&1 > /dev/null && YES=$?;
if [ $YES -eq 1 ]; then
read -t 30 -p "Press ENTER to remove, or CTRL-C to quit.";
${DOCKER} rmi $(${DOCKER} images -f dangling=true -q);
else
echo "Nothing to do... all groovy!";
fi
}
Works with:
$ docker --version
Docker version 17.05.0-ce, build 89658be
I also got this issue, I could resolve issue with below commands. this may be cause, the image's container is running or exit so before remove image you need to remove container
docker ps -a -f status=exited : this command shows all the exited containers so then copy container Id and then run below commands to remove container
docker rm #containerId : this command remove container this may be issue that mention "image has dependent child images"
Then try to remove image with below command
docker rmi #ImageId
I had this issue and none of the short answers here worked, even in the page mentioned by #tudor above. I thought I would share here how I got rid of the images. I came up with the idea that dependent images must be >= the size of the parent image, which helps identify it so we can remove it.
I listed the images in size order to see if I could spot any correlations:
docker images --format '{{.Size}}\t{{.Repository}}\t{{.Tag}}\t{{.ID}}' | sort -h -r | column -t
What this does, is use some special formatting from docker to position the image size column first, then run a human readable sort in reverse order. Then I restore the easy-to-read columns.
Then I looked at the <none> containers, and matched the first one in the list with a similar size. I performed a simple docker rmi <image:tag> on that image and all the <none> child images went with it.
The problem image with all the child images was actually the damn myrepo/getstarted-lab image I used when I first started playing with docker. It was because I had created a new image from the first test image which created the chain.
Hopefully that helps someone else at some point.
Trying to delete image id : b721d1cdaac7
docker rmi b721d1cdaac7 -f
Response : Error response from daemon: conflict: unable to delete b721d1cdaac7 (cannot be forced) - image has dependent child images
To delete all child images
docker image rm $(docker images --filter since=b721d1cdaac7 -q) -f
Suppose we have a Dockerfile
FROM ubuntu:trusty
CMD ping localhost
We build image from that without TAG or naming
docker build .
Now we have a success report "Successfully built 57ca5ce94d04"
If we see the docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
<none> <none> 57ca5ce94d04 18 seconds ago 188MB
ubuntu trusty 8789038981bc 11 days ago 188MB
We need to first remove the
docker rmi 57ca5ce94d04
Followed by
docker rmi 8789038981bc
By that image will be removed!
A forced removal of all as suggested by someone
docker rmi $(docker images -q) -f
Force deleting a list of images (exclude version 10, for example)
docker images | grep version | grep -v version10 > images.txt && for
img in $( awk -F" " '{print $3}' /root/images.txt ) ; do docker rmi
-f $img; done
Just simply use:
docker rmi <image:tag> -f
for example:
docker rmi ubuntu:latest -f
will remove image name ubuntu with tag name latest and -f is for forcefully removal.
it worked for me
Assure you haven't hit the rate-limit error if behind a corporate proxy.
If, by chance, you're behind a corporate proxy and using Windows, you may want to try this simple fix. I found several responses here helpful. However, even after running a docker image prune and other commands, I uncovered the lovely error (and root cause), which was previously masked: "toomanyrequests: You have reached your pull rate limit..."
Fix.
Open a Windows Terminal/DOS prompt and enter:
ipconfig/release
[...]
ipconfig/renew
This might just save you a call/ticket with IT. ;)
Image Layer: Repositories are often referred to as images or container images, but actually they are made up of one or more layers. Image layers in a repository are connected together in a parent-child relationship. Each image layer represents changes between itself and the parent layer.
The docker building pattern uses inheritance. It means the version i depends on version i-1. So, we must delete the version i+1 to be able to delete version i. This is a simple dependency.
If you wanna delete all images except the last one (the most updated) and the first (base) then we can export the last (the most updated one) using docker save command as below.
docker save -o <output_file> <your_image-id> | gzip <output_file>.tgz
Then, now, delete all the images using image-id as below.
docker rm -f <image-id i> | docker rm -f <image i-1> | docker rm -f <image-id i-2> ... <docker rm -f <image-id i-k> # where i-k = 1
Now, load your saved tgz image as below.
gzip -c <output_file.tgz> | docker load
see the image-id of your loaded image using docker ps -q. It doesn't have tag and name. You can simply update tag and name as done below.
docker tag <image_id> group_name/name:tag
you can just do this:
➜ ~ sudo docker rmi 4ed13257bb55 -f
Deleted: sha256:4ed13257bb5512b975b316ef482592482ca54018a7728ea1fc387e873a68c358
Deleted: sha256:4a478ca02e8d2336595dcbed9c4ce034cd15f01229733e7d93a83fbb3a9026d3
Deleted: sha256:96df41d1ce6065cf75d05873fb1f9ea9fed0ca86addcfcec7722200ed3484c69
Deleted: sha256:d95efe864c7096c38757b80fddad12819fffd68ac3cc73333ebffaa42385fded

Docker error cannot delete docker container, conflict: unable to remove repository reference

I want to remove the container at Docker, but an error occurs when you want to delete
My next step before removing the container, see the list of existing container
sts#Yudi:~/docker$ sudo docker ps -as
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES SIZE
78479ffeba5c ubuntu "/bin/bash" 42 hours ago Exited (0) 42 hours ago sharp_wescoff 81 B (virtual 187.7 MB)
0bd2b54678c7 training/webapp "python app.py" 5 days ago Exited (0) 5 days ago backstabbing_ritchie 0 B (virtual 323.7 MB)
0adbc74a3803 training/webapp "python app.py" 5 days ago Exited (143) 5 days ago drunk_feynman 0 B (virtual 323.7 MB)
one I want to delete the list, namely "training / webapp"
but an error that occurred
sts#Yudi:~/docker$ sudo docker rmi training/webapp
Error response from daemon: conflict: unable to remove repository reference "training/webapp" (must force) - container 0bd2b54678c7 is using its referenced image 54bb4e8718e8
Error: failed to remove images: [training/webapp]
Whether the container is running in the images?
Please help
There is a difference between docker images and docker containers. Check this SO Question.
In short, a container is a runnable instance of an image. which is why you cannot delete an image if there is a running container from that image. You just need to delete the container first.
docker ps -a # Lists containers (and tells you which images they are spun from)
docker images # Lists images
docker rm <container_id> # Removes a stopped container
docker rm -f <container_id> # Forces the removal of a running container (uses SIGKILL)
docker rmi <image_id> # Removes an image
# Will fail if there is a running instance of that image i.e. container
docker rmi -f <image_id> # Forces removal of image even if it is referenced in multiple repositories,
# i.e. same image id given multiple names/tags
# Will still fail if there is a docker container referencing image
Update for Docker 1.13+ [Since Jan 2017]
In Docker 1.13, we regrouped every command to sit under the logical object it’s interacting with
Basically, above commands could also be rewritten, more clearly, as:
docker container ls -a
docker image ls
docker container rm <container_id>
docker image rm <image_id>
Also, if you want to remove EVERYTHING you could use:
docker system prune -a
WARNING! This will remove:
all stopped containers
all networks not used by at least one container
all unused images
all build cache
First, remove the container names
$ sudo docker rm backstabbing_ritchie
The result
$ sudo docker rm backstabbing_ritchie
backstabbing_ritchie
delete the second part, which is listed on the container to be deleted
$ sudo docker rm drunk_feynman
drunk_feynman
Second, remove the container
$ sudo docker rmi training/webapp
The result
$ sudo docker rmi training/webapp
Untagged: training/webapp:latest
Deleted: 54bb4e8718e8600d78a5d7c62208c2f13c8caf0e4fe73d2bc0e474e93659c0b5
Deleted: f74dd040041eb4c032d3025fe38ea85de8075992bdce6789b694a44b20feb8de
Deleted: 7cbae69141977b99c44dc6957b032ad50c1379124d62b7d7d05ab7329b42348e
Deleted: abb991a4ed5e4cde2d9964aec4cccbe0015ba9cc9838b696e7a32e1ddf4a49bd
Deleted: 1952e3bf3d7e8e6a9b1e23bd4142e3c42ff7f4b7925122189704323593fd54ac
Deleted: f95ebd363bf27a7546deced7a41a4099334e37a3d2901fa3817e62bb1ade183f
Deleted: 20dd0c75901396d41a7b64d551ff04952084cc3947e66c67bae35759c80da338
Deleted: 2505b734adda3720799dde5004302f5edb3f2a2ff71438f6488b530b728ba666
Deleted: 2ee0b8f351f753f78f1178000ae37616eb5bf241d4ef041b612d58e1fd2aefdc
Deleted: 2ce633e3e9c9bd9e8fe7ade5984d7656ec3fc3994f05a97d5490190ef95bce8d
Deleted: 98b15185dba7f85308eb0e21196956bba653cf142b36dc08059b3468a01bf35d
Deleted: 515565c29c940355ec886c992231c6019a6cffa17ff1d2abdfc844867c9080c5
Deleted: 2880a3395eded9b748c94d27767e1e202f8d7cb06f1e40e18d1b1c77687aef77
Check the continer
$ sudo docker ps -as
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES SIZE
78479ffeba5c ubuntu "/bin/bash" 43 hours ago Exited (0) 43 hours ago sharp_wescoff 81 B (virtual 187.7 MB)
If you want to cleanup docker images and containers
CAUTION: this will flush everything
stop all containers
docker stop $(docker ps -a -q)
remove all containers
docker rm $(docker ps -a -q)
remove all images
docker rmi -f $(docker images -a -q)
you can use -f option to force delete the containers .
sudo docker rmi -f training/webapp
You may stop the containers using sudo docker stop training/webapp before deleting
If you have multiples docker containers launched, use this
$ docker rm $(docker ps -aq)
It will remove all the current dockers listed in the "ps -aq" command.
Source : aaam on https://github.com/docker/docker/issues/12487
1-Stop running container:
docker stop <container-id>
2-Remove container
docker rm <container-id>
3-Remove docker image
docker rmi <image-id>
list all your docker images:
docker images
list all existed docker containers:
docker ps -a
delete all the targeted containers, which is using the image that you want to delete:
docker rm <container-id>
delete the targeted image:
docker rmi <image-name:image-tag or image-id>
Noticed this is a 2-years old question, but still want to share my workaround for this particular question:
Firstly, run docker container ls -a to list all the containers you have and pinpoint the want you want to delete.
Secondly, delete the one with command docker container rm <CONTAINER ID> (If the container is currently running, you should stop it first, run docker container stop <CONTAINER ID> to gracefully stop the specified container, if it does not stop it for whatever the reason is, alternatively you can run docker container kill <CONTAINER ID> to force shutdown of the specified container).
Thirdly, remove the container by running docker container rm <CONTAINER ID>.
Lastly you can run docker image ls -a to view all the images and delete the one you want to by running docker image rm <hash>.
Deleting "network not found" in docker
Inspect the network which we are unable to delete
docker network inspect [<id> or <name>]
Disconnect the network
docker network disconnect -f [<networkID> or <networkName>] [<endpointName> or <endpointId>]
Delete unused networks
docker network prune
Remove docker images >
List all containers
docker container ls
List all images
docker image ls
Stop container by container id
docker container stop <container_id>
Remove container by container id
docker container rm <container_id>
If don't want stop and remove, can force remove
docker container rm -f <container_id>
Remove image
docker image rm <image_id>
Done!
Remove just the containers associated with a specific image
docker ps -a | grep training/webapp | cut -d ' ' -f 1 | xargs docker rm
ps -a: list all containers
grep training/webapp : filter out everything but the containers started from the training/webapp image
cut -d ' ' -f 1: list only the container ids (first field when delimited by space)
xargs docker rm : send the container id list output to the docker rm command to remove the container
Simply these two commands solve my issue.
Stop the particular container.
docker stop <container_id>
Forces removal of the image even if it is referenced in multiple repositories.
docker rmi -f <container_id>

How to remove old and unused Docker images

When running Docker for a long time, there are a lot of images in system. How can I remove all unused Docker images at once safety to free up the storage?
In addition, I also want to remove images pulled months ago, which have the correct TAG.
So, I'm not asking for removing untagged images only. I'm searching for a way to remove general unused images, which includes both untagged and other images such as pulled months ago with correct TAG.
(original answer see below)
Update Sept. 2016: Docker 1.13: PR 26108 and commit 86de7c0 introduce a few new commands to help facilitate visualizing how much space the docker daemon data is taking on disk and allowing for easily cleaning up "unneeded" excess.
docker system prune will delete ALL dangling data (i.e. In order: containers stopped, volumes without containers and images with no containers). Even unused data, with -a option.
You also have:
docker container prune
docker image prune
docker network prune
docker volume prune
For unused images, use docker image prune -a (for removing dangling and ununsed images).
Warning: 'unused' means "images not referenced by any container": be careful before using -a.
As illustrated in A L's answer, docker system prune --all will remove all unused images not just dangling ones... which can be a bit too much.
Combining docker xxx prune with the --filter option can be a great way to limit the pruning (docker SDK API 1.28 minimum, so docker 17.04+)
The currently supported filters are:
until (<timestamp>) - only remove containers, images, and networks created before given timestamp
label (label=<key>, label=<key>=<value>, label!=<key>, or label!=<key>=<value>) - only remove containers, images, networks, and volumes with (or without, in case label!=... is used) the specified labels.
See "Prune images" for an example.
Warning: there is no "preview" or "--dry-run" option for those docker xxx prune commands.
This is requested with moby/moby issue 30623 since 2017, but seems tricky to be implemented (Aug. 2022)
Having a more representative overview of what will be pruned will be quite complicated, for various reasons;
race conditions (can be resolved by documenting the limitations);
A container/image/volume/network may not be in use at the time that "dry run" is used, but may be in use the moment the actual prune is executed (or vice-versa), so dry run will always be an "approximation" of what will be pruned.
the more difficult part is due to how objects (containers, images, networks etc.) depend on each other.
For example, an image can be deleted if it no longer has references to it (no more tags, no more containers using it); this is the reason that docker system prune deletes objects in a specific order (first remove all unused containers, then remove unused images).
In order to replicate the same flow for "dry-run", it will be needed to temporarily construct representation of all objects and where they're referenced based on that (basically; duplicate all reference-counters, and then remove references from that "shadow" representation).
Finally; with the work being done on integrating the containerd snapshotter (image and layer store), things may change more;
For example, images can now be multi-arch, and (to be discussed), "pruning" could remove unused variants (architectures) from an image to clean up space, which brings another dimension to calculating "what can be removed".
Original answer (Sep. 2016)
I usually do:
docker rmi $(docker images --filter "dangling=true" -q --no-trunc)
I have an [alias for removing those dangling images: drmi]13
The dangling=true filter finds unused images
That way, any intermediate image no longer referenced by a labelled image is removed.
I do the same first for exited processes (containers)
alias drmae='docker rm $(docker ps -qa --no-trunc --filter "status=exited")'
As haridsv points out in the comments:
Technically, you should first clean up containers before cleaning up images, as this will catch more dangling images and less errors.
Jess Frazelle (jfrazelle) has the bashrc function:
dcleanup(){
docker rm -v $(docker ps --filter status=exited -q 2>/dev/null) 2>/dev/null
docker rmi $(docker images --filter dangling=true -q 2>/dev/null) 2>/dev/null
}
To remove old images, and not just "unreferenced-dangling" images, you can consider docker-gc:
A simple Docker container and image garbage collection script.
Containers that exited more than an hour ago are removed.
Images that don't belong to any remaining container after that are removed.
Update the second (2017-07-08)
Refer (again) to VonC, using the even more recent system prune. The impatient can skip the prompt with the -f, --force option:
docker system prune -f
The impatient and reckless can additionally remove "unused images not just the dangling ones" with the -a, --all option:
docker system prune -af
https://docs.docker.com/engine/reference/commandline/system_prune/
Update
Refer to VonC's answer which uses the recently added prune commands. Here is the corresponding shell alias convenience:
alias docker-clean=' \
docker container prune -f ; \
docker image prune -f ; \
docker network prune -f ; \
docker volume prune -f '
Old answer
Delete stopped (exited) containers:
$ docker ps --no-trunc -aqf "status=exited" | xargs docker rm
Delete unused (dangling) images:
$ docker images --no-trunc -aqf "dangling=true" | xargs docker rmi
If you have exercised extreme caution with regard to irrevocable data loss, then you can delete unused (dangling) volumes (v1.9 and up):
$ docker volume ls -qf "dangling=true" | xargs docker volume rm
Here they are in a convenient shell alias:
alias docker-clean=' \
docker ps --no-trunc -aqf "status=exited" | xargs docker rm ; \
docker images --no-trunc -aqf "dangling=true" | xargs docker rmi ; \
docker volume ls -qf "dangling=true" | xargs docker volume rm'
References
docker ps -f
docker rm
docker images -f
docker rmi
Docker v1.9.0 release notes
docker volume ls
docker volume rm
The other answers are great, specifically:
docker system prune # doesn't clean out old images
docker system prune --all # cleans out too much
But I needed something in the middle of the two commands so the filter option was what I needed:
docker image prune --all --filter "until=4320h" # delete images older than 6 months ago; 4320h = 24 hour/day * 30 days/month * 6 months
For reference: https://docs.docker.com/config/pruning/#prune-images
To remove old tagged images that are more than a month old:
$ docker images --no-trunc --format '{{.ID}} {{.CreatedSince}}' \
| grep ' months' | awk '{ print $1 }' \
| xargs --no-run-if-empty docker rmi
Note that it'll fail to remove images that are used by a container, referenced in a repository, has dependent child images... which is probably what you want. Else just add -f flag.
Example of /etc/cron.daily/docker-gc script:
#!/bin/sh -e
# Delete all stopped containers (including data-only containers).
docker ps -a -q --no-trunc --filter "status=exited" | xargs --no-run-if-empty docker rm -v
# Delete all tagged images more than a month old
# (will fail to remove images still used).
docker images --no-trunc --format '{{.ID}} {{.CreatedSince}}' | grep ' months' | awk '{ print $1 }' | xargs --no-run-if-empty docker rmi || true
# Delete all 'untagged/dangling' (<none>) images
# Those are used for Docker caching mechanism.
docker images -q --no-trunc --filter dangling=true | xargs --no-run-if-empty docker rmi
# Delete all dangling volumes.
docker volume ls -qf dangling=true | xargs --no-run-if-empty docker volume rm
According to the doc, the following command will delete images older than 48 hours.
$ docker image prune --all --filter until=48h
Assuming you have Docker 1.13 or higher you can just use the prune commands. For your question specifically for removing old images, you want the first one.
# Remove unused images
docker image prune
# Remove stopped containers.
docker container prune
# Remove unused volumes
docker volume prune
# Remove unused networks
docker network prune
# Command to run all prunes:
docker system prune
I would recommend not getting used to using the docker system prune command. I reckon users will accidentally remove things they don't mean to. Personally, I'm going to mainly be using the docker image prune and docker container prune commands.
Until now (Docker version 1.12) we are using the following command to delete all the running containers. Also, if we want to delete the volumes, we can do that manually using its respective tag -v in the following command.
Delete all Exited Containers
docker rm $(docker ps -q -f status=exited)
Delete all Stopped Containers
docker rm $(docker ps -a -q)
Delete All Running and Stopped Containers
docker stop $(docker ps -a -q)
docker rm $(docker ps -a -q)
Remove all containers, without any criteria
docker container rm $(docker container ps -aq)
But, in version 1.13 and above, for complete system and cleanup, we can directly user the following command:
docker system prune
All unused containers, images, networks and volumes will get deleted. We can also do this using the following commands that clean up the individual components:
docker container prune
docker image prune
docker network prune
docker volume prune
This worked for me:
docker rmi $(docker images | grep "^<none>" | awk "{print $3}")
I recently wrote a script to solve this on one of my servers:
#!/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"}' \
))
# Get all the images currently available
ALL_IMAGES=($( \
docker images --format '{{.Repository}}:{{.Tag}}' | \
sort -u \
))
# Remove the unused images
for i in "${ALL_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
Here is a script to clean up Docker images and reclaim the space.
#!/bin/bash -x
## Removing stopped container
docker ps -a | grep Exited | awk '{print $1}' | xargs docker rm
## If you do not want to remove all container you can have filter for days and weeks old like below
#docker ps -a | grep Exited | grep "days ago" | awk '{print $1}' | xargs docker rm
#docker ps -a | grep Exited | grep "weeks ago" | awk '{print $1}' | xargs docker rm
## Removing Dangling images
## There are the layers images which are being created during building a Docker image. This is a great way to recover the spaces used by old and unused layers.
docker rmi $(docker images -f "dangling=true" -q)
## Removing images of perticular pattern For example
## Here I am removing images which has a SNAPSHOT with it.
docker rmi $(docker images | grep SNAPSHOT | awk '{print $3}')
## Removing weeks old images
docker images | grep "weeks ago" | awk '{print $3}' | xargs docker rmi
## Similarly you can remove days, months old images too.
Original script
https://github.com/vishalvsh1/docker-image-cleanup
Usually Docker keeps all temporary files related to image building and layers at
/var/lib/docker
This path is local to the system, usually at THE root partition, "/".
You can mount a bigger disk space and move the content of /var/lib/docker to the new mount location and make a symbolic link.
This way, even if Docker images occupy space, it will not affect your system as it will be using some other mount location.
Original post: Manage Docker images on local disk
I'm using this command:
export BEFORE_DATETIME=$(date --date='10 weeks ago' +"%Y-%m-%dT%H:%M:%S.%NZ")
docker images -q | while read IMAGE_ID; do
export IMAGE_CTIME=$(docker inspect --format='{{.Created}}' --type=image ${IMAGE_ID})
if [[ "${BEFORE_DATETIME}" > "${IMAGE_CTIME}" ]]; then
echo "Removing ${IMAGE_ID}, ${BEFORE_DATETIME} is earlier then ${IMAGE_CTIME}"
docker rmi -f ${IMAGE_ID};
fi;
done
This will remove all images whose creation time is greater than 10 weeks ago.
If you want to remove images pulled X months ago, you can try the below example which remove images created three months ago:
three_months_old_images=`docker images | grep -vi "<none>" | tr -s ' ' | cut -d" " -f3,4,5,6 | grep "3 months ago" | cut -d" " -f1`
docker rmi $three_months_old_images
To prune all images and volumes as well
docker system prune -af --volumes
docker system prune -a
(You'll be asked to confirm the command. Use -f to force run, if you know what you're doing.)
#VonC already gave a very nice answer, but for completeness here is a little script I have been using---and which also nukes any errand Docker processes should you have some:
#!/bin/bash
imgs=$(docker images | awk '/<none>/ { print $3 }')
if [ "${imgs}" != "" ]; then
echo docker rmi ${imgs}
docker rmi ${imgs}
else
echo "No images to remove"
fi
procs=$(docker ps -a -q --no-trunc)
if [ "${procs}" != "" ]; then
echo docker rm ${procs}
docker rm ${procs}
else
echo "No processes to purge"
fi
To remove tagged images which have not container running, you will have to use a little script:
#!/bin/bash
# remove not running containers
docker rm $(docker ps -f "status=exited" -q)
declare -A used_images
# collect images which has running container
for image in $(docker ps | awk 'NR>1 {print $2;}'); do
id=$(docker inspect --format="{{.Id}}" $image);
used_images[$id]=$image;
done
# loop over images, delete those without a container
for id in $(docker images --no-trunc -q); do
if [ -z ${used_images[$id]} ]; then
echo "images is NOT in use: $id"
docker rmi $id
else
echo "images is in use: ${used_images[$id]}"
fi
done
Remove old containers weeks ago.
docker rm $(docker ps -a | grep "weeks" | awk '{ print $1; }')
Remove old images weeks ago. Be careful. This will remove base images which was created weeks ago but which your new images might be using.
docker rmi $(docker images | grep 'weeks' | awk '{ print $3; }')
How to remove a tagged image
docker rmi the tag first
docker rmi the image.
# that can be done in one docker rmi call e.g.: #
docker rmi <repo:tag> <imageid>
(this works Nov 2016, Docker version 1.12.2)
e.g.
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
usrxx/the-application 16112805 011fd5bf45a2 12 hours ago 5.753 GB
usryy/the-application vx.xx.xx 5af809583b9c 3 days ago 5.743 GB
usrzz/the-application vx.xx.xx eef00ce9b81f 10 days ago 5.747 GB
usrAA/the-application vx.xx.xx 422ba91c71bb 3 weeks ago 5.722 GB
usrBB/the-application v1.00.18 a877aec95006 3 months ago 5.589 GB
$ docker rmi usrxx/the-application:16112805 && docker rmi 011fd5bf45a2
$ docker rmi usryy/the-application:vx.xx.xx && docker rmi 5af809583b9c
$ docker rmi usrzz/the-application:vx.xx.xx eef00ce9b81f
$ docker rmi usrAA/the-application:vx.xx.xx 422ba91c71bb
$ docker rmi usrBB/the-application:v1.00.18 a877aec95006
e.g. Scripted remove anything older than 2 weeks.
IMAGESINFO=$(docker images --no-trunc --format '{{.ID}} {{.Repository}} {{.Tag}} {{.CreatedSince}}' |grep -E " (weeks|months|years)")
TAGS=$(echo "$IMAGESINFO" | awk '{ print $2 ":" $3 }' )
IDS=$(echo "$IMAGESINFO" | awk '{ print $1 }' )
echo remove old images TAGS=$TAGS IDS=$IDS
for t in $TAGS; do docker rmi $t; done
for i in $IDS; do docker rmi $i; done
docker rm $(docker ps -faq)
docker rmi $(docker ps -faq)
-f force
-a all
-q in the mode
First, run docker images to see list of images and copy IMAGE HASH ID into clipboard.
Run docker rmi -f <Image>
Remember option -f is force deleting.
Occasionally I have run into issues where Docker will allocate and continue to use disk space, even when the space is not allocated to any particular image or existing container. The latest way I generated this issue accidentally was using "docker-engine" centos build instead of "docker" in RHEL 7.1. What seems to happen is sometimes the container clean-ups are not completed successfully and then the space is never reused. When the 80GB drive I allocated as / was filled with /var/lib/docker files I had to come up with a creative way to resolve the issue.
Here is what I came up with. First to resolve the disk full error:
Stop docker: systemctl stop docker
Allocated a new drive mounted as say /mnt/docker .
Move all the files in /var/lib/docker to /mnt/docker . I used the command:
rsync -aPHSx --remove-source-files /var/lib/docker/ /mnt/docker/
Mount the new drive to /var/lib/docker.
At this point I no longer had a disk full error, but I was still wasting a huge amount of space. The next steps are to take care of that.
Start Docker: systemctl start docker
Save the all the images:
docker save $(docker images |sed -e '/^<none>/d' -e '/^REPOSITORY/d' -e 's,[ ][ ]*,:,' -e 's,[ ].*,,') > /root/docker.img
Uninstall docker.
Erase everything in /var/lib/docker:
rm -rf /var/lib/docker/[cdintv]*
Reinstall docker
Enable docker: systemctl enable docker
Start docker: systemctl start docker
Restore images:
docker load < /root/docker.img
Start any persistent containers you need running.
This dropped my disk usage from 67 GB for docker to 6 GB for docker.
I do not recommend this for everyday use. But it is useful to run when it looks like docker has lost track of used disk space do to software errors, or unexpected reboots.
docker rm `docker ps -aq`
or
docker rm $(docker ps -q -f status=exited)
If you wish to automatically/periodically clean up exited containers and remove images and volumes that aren't in use by a running container you can download the image meltwater/docker-cleanup.
Just run:
docker run -d -v /var/run/docker.sock:/var/run/docker.sock:rw -v /var/lib/docker:/var/lib/docker:rw --restart=unless-stopped meltwater/docker-cleanup:latest
It runs every 30 minutes by default. You can however set the delay time by using this flag in seconds (DELAY_TIME=1800 option).
More details: https://github.com/meltwater/docker-cleanup/blob/master/README.md
If you build these pruned images yourself (from some other, older base images) please be careful with the accepted solutions above based on docker image prune, as the command is blunt and will try to remove also all dependencies required by your latest images (the command should be probably renamed to docker image*s* prune).
The solution I came up for my docker image build pipelines (where there are daily builds and tags=dates are in the YYYYMMDD format) is this:
# carefully narrow down the image to be deleted (to avoid removing useful static stuff like base images)
my_deleted_image=mirekphd/ml-cpu-py37-vsc-cust
# define the monitored image (tested for obsolescence), which will be usually the same as deleted one, unless deleting some very infrequently built image which requires a separate "clock"
monitored_image=mirekphd/ml-cache
# calculate the oldest acceptable tag (date)
date_week_ago=$(date -d "last week" '+%Y%m%d')
# get the IDs of obsolete tags of our deleted image
# note we use monitored_image to test for obsolescence
my_deleted_image_obsolete_tag_ids=$(docker images --filter="before=$monitored_image:$date_week_ago" | grep $my_deleted_image | awk '{print $3}')
# remove the obsolete tags of the deleted image
# (note it typically has to be forced using -f switch)
docker rmi -f $my_deleted_image_obsolete_tag_ids
See the official reference for docker system prune
docker system prune will remove:
all stopped containers
all networks not used by at least one container
all dangling images
all build cache
docker system prune -a will do the same, but in additional to removing all dangling images, it will more broadly remove:
all images without at least one container associated to them
What are dangling images?
Docker images consist of multiple layers that get wrapped inside a parent 'container layer' when the overall container image is generated from a Dockerfile. Dangling images are layers that have no relationship to any other tagged images, and will therefore never have any use within any new containers that are built. They no longer serve a purpose and consume disk space.
For example a dangling image can be created by the following process:
Build a named image my-image from Dockerfile, without specifying any tag:
FROM ubuntu:latest
CMD ["echo", "Hello World"]
docker build -t my-image
docker images
REPOSITORY TAG IMAGE ID
my-image latest 7ed6e7202eca <--- created, not dangling
ubuntu latest 825d55fb6340
Update the Dockerfile:
FROM ubuntu:latest
CMD ["echo", "Hello, World!"]
Rebuild image re-using the previous name, without specifying any tag:
docker build -t my-image
docker images
REPOSITORY TAG IMAGE ID
my-image latest da6e74196f66 <--- replacement layer
<none> <none> 7ed6e7202eca <--- previous layer, now dangling
ubuntu latest 825d55fb6340
The build created a new my-image layer. As we can see, the layer that was originally created is still there, but its name and tag are set to <none>:<none>. It will never be possible for this layer to be associated with any docker container layer, which means it's 'dangling'
What are images without at least one container associated to them?
An unused image means that it has not been assigned or used in a container. For example, docker ps -a will list all of your running and stopped containers. Any image being used by any of these containers is a "used image".
When running docker system prune -a, it will remove both unused and dangling images. Any image with at least one container associated to it will not be affected.
There is sparrow plugin docker-remove-dangling-images you can use to clean up stopped containers and unused (dangling) images:
$ sparrow plg run docker-remove-dangling-images
It works both for Linux and Windows OS.
If you have a lot of them, it can be really tedious to remove them, but lucky for us Docker has a few commands to help us eliminate dangling images. In older versions of Docker (and this still works today), you can delete dangling images on their own by running docker rmi -f $(docker images -f "dangling=true" -q) .
I usually do docker rm -f $(docker ps -a -q) and docker system prune to purge all dangling containers.
The below command will help to remove all unused and old images from local repository
==> docker system prune --all

Resources