859

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.

mohan08p
  • 3,723
  • 1
  • 22
  • 35
Quanlong
  • 19,782
  • 10
  • 62
  • 75

27 Answers27

1560

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:

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.


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]13: drmi

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.
VonC
  • 1,042,979
  • 435
  • 3,649
  • 4,283
  • 31
    Is there documentation on what `"dangling=true"` really means? – CivFan Sep 22 '15 at 17:33
  • 1
    This script cannot remove some images pulled months ago – Quanlong Sep 22 '15 at 17:35
  • @Quanlong I have edited the answer and referenced a project that do remove old images. – VonC Sep 22 '15 at 17:44
  • 2
    `dcleanup` is awesome! – Quanlong Oct 29 '15 at 15:30
  • Technically, you should first clean up containers before cleaning up images, as this will catch more dangling images and less errors. – haridsv Jun 24 '16 at 06:44
  • @haridsv I agree, and have included your comment in the answer for more visibility. – VonC Jun 24 '16 at 07:01
  • @CivFan for the sake of completeness: https://docs.docker.com/engine/reference/commandline/volume_ls/#dangling and https://docs.docker.com/engine/reference/commandline/images/#/filtering are helpful. "Images that are the leaves of image trees". – s-low Aug 17 '16 at 08:33
  • Unused containers can be easily removed using docker rm $(docker ps -q -f status=exited) – Gaurav Ojha Sep 28 '16 at 06:43
  • @GauravOjha isn't it what my alias drmae does? (the one mentioned in my answer) – VonC Sep 28 '16 at 06:44
  • @VonC ohh yes, you're right! its the same, never mind! – Gaurav Ojha Sep 28 '16 at 06:56
  • To list all dangling images before removing them, you can run this: `docker images --filter "dangling=true"`. – Johnny Oshika Nov 10 '16 at 16:28
  • Docker system prune does not remove unused images. '-a' is required for that – herm Jul 28 '17 at 07:39
  • 4
    @herm First, `docker system prune` removes much more than just images. Make sure to use `docker image prune` instead. And be **very careful** with `-a`: a `docker system prune -a` can have devastating effect (removing volumes as well). Finally, yes, `-a` removes unused images, I will edit the answer. – VonC Jul 28 '17 at 08:47
  • If you want to delete all images except one: `docker rmi $(docker images -q | grep -v IMAGE_TO_KEEP_ID)` – lifeisfoo Aug 04 '17 at 15:28
  • @VonC `docker system prune` doesn't remove unused images though, it removes all stopped containers, all volumes not used by at least one container, all networks not used by at least one container, and all *dangling* images. – thrnio Oct 05 '17 at 20:47
  • @thrnio yes? That is why I added "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`." – VonC Oct 05 '17 at 20:49
  • @VonC Right, but above that you have "`docker system prune` will delete ALL unused data (i.e. In order: containers stopped, volumes without containers and images with no containers)." which isn't completely accurate. – thrnio Oct 06 '17 at 18:30
  • What is difference between dangling and unused images ? – Shaiju T Oct 25 '18 at 07:33
  • 2
    @stom : 'unused' means "images not referenced by any container, but dangling means not tagged at all (just an id). – VonC Oct 25 '18 at 11:36
  • 1
    The `--filter` documentation has no information about what available filter labels exist, so kudos on somehow discovering that `dangling` is a valid filter label. I need to be able to filter by `image id`, but anything I try is an invalid filter label. – cowlinator Jan 23 '20 at 03:54
  • Still have files I created when I exec'd into the old container. How do I clean everything (as in get absolutely everything, nothing lingering, delete it all, wipe, destroy, delete, nothing remaining, erase all trace of old container/volumes)? I want a completely FRESH container, with no trace of what went before it. Format hard drive? Did docker system prune - didn't delete the files I'd created in the previous container. – garryp Apr 29 '20 at 14:27
  • 1
    @garryp Not so much formatting the drive, but at least delete `/var/lib/docker`, as I mentioned here https://stackoverflow.com/a/42265926/6309: do consider the warnings in the answer though. That *really* delete *everything*. – VonC Apr 29 '20 at 14:33
  • The images having name and tag as none in `docker images` are dangled. How to check their size? Also, the images having name and tag as none in `docker images -a` are intermediate images. Can they be deleted and how to check their size? – variable May 05 '20 at 16:56
  • @variable Not sure about the size. But you can remove dangling images: https://stackoverflow.com/a/53221540/6309. `docker image prune -a` would remove both ununsed and dangling images: https://stackoverflow.com/a/45143234/6309 – VonC May 05 '20 at 17:03
  • But intermediary images are same as dangling images? Why are they not auto cleared. Does the docker try to reuse them at any point? – variable May 05 '20 at 17:05
  • @variable that is what https://stackoverflow.com/a/53224187/6309 documents. – VonC May 05 '20 at 17:07
  • They mention that "They don't result into a disk space problem ". But don't give reason and how to check size – variable May 05 '20 at 17:11
  • @variable For that, you need to read http://www.projectatomic.io/blog/2015/07/what-are-docker-none-none-images/ – VonC May 05 '20 at 17:13
  • Yes it doesn't say why it is not a disk space problem. If you can point me to where they it will be helpful. – variable May 05 '20 at 17:14
  • @variable "Next it downloaded the layer `ded7cd95e059` and named it `fedora:latest`. The `fedora:latest` image is composed of both these layers, forming a parent child hierarchical relationship as shown below.": that means the size of the official layer `fedora:latest` includes the `none:none` one. – VonC May 05 '20 at 17:17
  • Oh so deleting the fedora:latest would get rid of the none:none or do they (intermediate) remain forever and need manual pruning please? – variable May 05 '20 at 17:19
  • @variable I believe it would get rid of the "good" none:none indeed: you can put your question (about none:none size) as a separate question; that will help others (instead of those comments) – VonC May 05 '20 at 17:20
139

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:

rubicks
  • 3,733
  • 1
  • 25
  • 33
  • 3
    I'd exercise caution with the volume cleanup. Both automatically created container volumes and named volumes that aren't currently in use are listed together with the dangling=true. – BMitch Jun 24 '16 at 12:35
  • 1
    @BMitch, you're absolutely correct; I've added a stern warning to the `docker volume rm` recipe. I'll welcome any suggestions you have. – rubicks Jun 24 '16 at 16:07
  • 1
    I'd love docker to give us a different filter option for the named volumes. If I come up with a good workaround, I'll be sure to share. – BMitch Jun 24 '16 at 19:10
  • @BMitch, docker [v1.12.0](https://github.com/docker/docker/releases/tag/v1.12.0) added name/driver filter support for `volume`. – rubicks Sep 21 '16 at 18:50
  • 2
    yes, but unfortunately it doesn't separate the named volume from an anonymous container volume with a simple flag. The command I've been using is `docker volume ls -qf dangling=true | egrep '^[a-z0-9]{64}$' | xargs --no-run-if-empty docker volume rm` which will work as long as you never name your volumes with something similar to a guid. I may tweak this for the new filter syntax. – BMitch Sep 21 '16 at 20:09
  • 1
    Removing unused (dangling) volumes really help us! – Kane Sep 30 '16 at 13:46
  • this is the first answer that works for me on Windows 7... finally! and thank you! :) – Zathrus Writer Dec 13 '16 at 07:38
  • Could someone describe what "extreme caution" would look like? What kinds of destruction could happen? – Ken Williams Jan 13 '17 at 23:07
  • @KenWilliams, in this context, "extreme caution" means making sure that you really _don't_ care about any data you left in any dangling volume (one with no association to any existing container). The kind of destruction you risk is the deletion of data residing in such "orphaned" volumes. – rubicks Jan 14 '17 at 15:04
  • 1
    Can't stop laughing at the `-af` flags being the most effective. That's the only thing that worked for me. Apparently old containers I created and stopped weeks ago don't count as "dangling." – sudo Apr 23 '18 at 20:22
  • 1
    @sudo, sometimes the universe gives you a gift. :-) – rubicks Apr 24 '18 at 11:29
63

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
Wernight
  • 32,087
  • 22
  • 110
  • 128
  • 2
    +1 For the command to delete old docker images. It's a bit hacky, but the solution is original and works perfectly :) – Rick Jan 30 '17 at 13:59
  • 3
    This is nice however I think this only deletes docker images that are at least **4 months** old. `.CreatedSince` uses weeks as the unit of time in the output even on images that are a lot of weeks old, e.g. `12 weeks`. – joelittlejohn Mar 06 '17 at 15:12
  • 2
    This worked for me, nice and simple: `docker images | grep ' months' | awk '{ print $3 }' | xargs --no-run-if-empty docker rmi -f` – Kent Bull Jun 15 '17 at 22:13
55

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

Hope that helps :)

For reference: https://docs.docker.com/config/pruning/#prune-images

Zhao Li
  • 3,184
  • 5
  • 28
  • 43
28

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Programster
  • 11,048
  • 8
  • 43
  • 51
  • 4
    you dont want to prune unused networks do you? like, if all containers are stopped, and I delete those networks, how will they containers work if I start them. Do networks get created along with docker run ? – Northstrider Mar 04 '17 at 14:31
  • @meffect I completely agree and god spot that I had left network pruning out. I have included that and added a part at the end stating that I wouldn't recommend using `docker system prune` but the individual prunes. – Programster Mar 04 '17 at 18:47
21

The following command will delete images older than 48 hours.

$ docker image prune --all --filter until=48h
illagrenan
  • 4,146
  • 1
  • 38
  • 48
Shree Prakash
  • 1,315
  • 2
  • 15
  • 29
  • 1
    Using filters is also possible to list every versions before a specified version: `docker image ls --all --filter reference=monolito --filter before=monolito:0.1.8` and then apply a rmi command to delete. `docker rmi $(docker image ls -q --all --filter reference=monolito --filter before=monolito:0.1.8)` – rodvlopes Jan 03 '20 at 13:28
17

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
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
mohan08p
  • 3,723
  • 1
  • 22
  • 35
15

This worked for me:

docker rmi $(docker images | grep "^<none>" | awk "{print $3}")
Mahmoud Zalt
  • 24,048
  • 7
  • 74
  • 78
10

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
Ell Neal
  • 5,844
  • 2
  • 27
  • 54
8

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

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
7

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Yonatan Kiron
  • 2,148
  • 16
  • 24
6

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
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
spectre007
  • 1,309
  • 7
  • 16
  • 1
    This is not correct. This removes images *created* 3 months ago, not images *pulled* 3 months ago (if you pull them from a remote source, they can already be 3 months old right away). – Andrew Ferrier May 04 '16 at 20:49
  • This helped me to create more filters, based on different criterias – david.sansay May 20 '16 at 15:47
4

To prune all images and volumes as well
docker system prune -af --volumes

Zaytsev Dmitry
  • 1,627
  • 2
  • 17
  • 29
3

@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
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Dirk Eddelbuettel
  • 331,520
  • 51
  • 596
  • 675
  • Works great but can still get `Error response from daemon: You cannot remove a running container`. Added `docker kill $(docker ps -q)` before line 3 to address – Vincent Jun 02 '18 at 20:20
  • Why not use `$(docker images -q)` instead of `$(docker images | awk '// { print $3 }')`? – SeF Apr 10 '19 at 17:28
  • 1
    @SeF: If I do `docker images -q` I get a vector of image ids, nothing else. If I do what I do I get more -- allowing me to filter on `` as I do here. Makes sense? – Dirk Eddelbuettel Apr 10 '19 at 18:43
3

docker system prune -a

(You'll be asked to confirm the command. Use -f to force run, if you know what you're doing.)

Vojtech Vitek
  • 19,072
  • 3
  • 27
  • 32
  • 7
    **This is dangerous**, see other comments about `docker system prune` removing even named volumes with `-a`. – RichVel Aug 23 '17 at 15:03
2

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
ospider
  • 5,563
  • 1
  • 33
  • 38
2

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:

  1. Stop docker: systemctl stop docker

  2. Allocated a new drive mounted as say /mnt/docker .

  3. 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/
    
  4. 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.

  1. Start Docker: systemctl start docker

  2. Save the all the images:

    docker save $(docker images |sed -e '/^<none>/d' -e '/^REPOSITORY/d' -e 's,[ ][ ]*,:,' -e 's,[ ].*,,') > /root/docker.img
    
  3. Uninstall docker.

  4. Erase everything in /var/lib/docker:

    rm -rf /var/lib/docker/[cdintv]*
    
  5. Reinstall docker

  6. Enable docker: systemctl enable docker

  7. Start docker: systemctl start docker

  8. Restore images:

    docker load < /root/docker.img
    
  9. 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.

rubo77
  • 15,234
  • 23
  • 111
  • 195
briemers
  • 87
  • 3
2

How to remove a tagged image

  1. docker rmi the tag first

  2. 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
gaoithe
  • 3,271
  • 1
  • 25
  • 31
2

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; }')

Antony.H
  • 915
  • 9
  • 9
2
docker rm $(docker ps -faq)
docker rmi $(docker ps -faq)

-f force

-a all

-q in the mode

Hamit YILDIRIM
  • 3,061
  • 18
  • 29
1
docker rm `docker ps -aq`

or

docker rm $(docker ps -q -f status=exited)
mainframer
  • 15,543
  • 11
  • 43
  • 63
  • 3
    I think this answer is dangerous because those commands remove containers. Firstly, OP was asking how to remove images, not containers. And more importantly, those commands may cause to loss data due to people may have some valuable data in exited containers. – u.unver34 Feb 16 '17 at 17:35
  • You should describe potentially unwanted results of applying these commands on production server. – Daniel May 29 '18 at 16:57
  • this removes containers, not images. – SeF Apr 10 '19 at 17:29
1

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

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Innocent Anigbo
  • 3,130
  • 1
  • 13
  • 17
1

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.

Le Khiem
  • 541
  • 4
  • 9
1

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
mirekphd
  • 1,539
  • 12
  • 22
0

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.

Alexey Melezhik
  • 830
  • 6
  • 24
0

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) .

Philip Mutua
  • 4,150
  • 5
  • 23
  • 48
0

I usually do docker rm -f $(docker ps -a -q) and docker system prune to purge all dangling containers.

Bhargav Panth
  • 149
  • 1
  • 9