1305

This question is related to Should I be concerned about excess, non-running, Docker containers?.

I'm wondering how to remove old containers. The docker rm 3e552code34a lets you remove a single one, but I have lots already. docker rm --help doesn't give a selection option (like all, or by image name).

Maybe there is a directory in which these containers are stored where I can delete them easily manually?

Community
  • 1
  • 1
qkrijger
  • 24,730
  • 6
  • 32
  • 37
  • 21
    **You should also consider cleaning orphaned docker volumes.** I often find that they consume much more space than old containers and old images. Good script for removing orphaned docker volumes is available at: https://github.com/chadoe/docker-cleanup-volumes. – Nemanja Trifunovic Dec 01 '15 at 18:06
  • Maybe https://github.com/chadoe/docker-cleanup-volumes can help you. – Mihai8 Sep 13 '16 at 19:34
  • You can also use `docker run`with the `--rm` flag which would make the container ephemeral, removing all container files after the run. – Gordon Sep 21 '16 at 05:51
  • I agree with @NemanjaTrifunovic . Pay attention. Keep this in your toolbok: docker volume ls -f dangling=true – bitfox Sep 21 '16 at 17:51
  • 13
    With docker 1.13 (Q4 2016), you can also consider the new `docker system prune` command. See [my answer below](http://stackoverflow.com/a/39860665/6309). – VonC Oct 04 '16 at 19:52
  • @VonC this isn't working for me at `Docker version 1.12.3, build 6b644ec` :) – ReynierPM Dec 19 '16 at 15:21
  • 1
    Use the docker management tool `Portainer ` We can manage`all the old containers, non using volumes and images` by using this tool Its a simple management UI for dockers `Please refer my update below on how to deploy the application` – Anish Varghese Nov 22 '18 at 04:47

62 Answers62

1577

Since Docker 1.13.x you can use Docker container prune:

docker container prune

This will remove all stopped containers and should work on all platforms the same way.

There is also a Docker system prune:

docker system prune

which will clean up all unused containers, networks, images (both dangling and unreferenced), and optionally, volumes, in one command.


For older Docker versions, you can string Docker commands together with other Unix commands to get what you need. Here is an example on how to clean up old containers that are weeks old:

$ docker ps --filter "status=exited" | grep 'weeks ago' | awk '{print $1}' | xargs --no-run-if-empty docker rm

To give credit, where it is due, this example is from https://twitter.com/jpetazzo/status/347431091415703552.

slhck
  • 30,965
  • 24
  • 125
  • 174
Ken Cochrane
  • 68,551
  • 9
  • 45
  • 57
  • Thank you! By the way, it is not possible to tag containers, is it? For instance, one could have a database image, of which an instance (container) might contain valuable data. Another valuable tool might be to flag a container as being 'used', thus protecting it from 'docker rm'. – qkrijger Jun 22 '13 at 10:36
  • note that I will put these comments in the issue that you mentioned – qkrijger Jun 22 '13 at 10:55
  • 95
    Similar command to remove all untagged images: `docker images | grep "" | awk '{print $3}' | xargs docker rmi` – Mohan Raj Sep 20 '13 at 21:29
  • This solution works well if you want to remove containers depending on their age. What I'd like to do (and I'm assuming I'm not alone in this) is to remove everything that's not in the dependency graph of some specified container(s). I've found that during development of a Dockerfile, the number of containers is growing very quickly. Furthermore, just deleting everything is not ideal either in case you have some long running compilations in your dockerfile. If someone has an idea on how to handle this I'd be very glad for your input. – Michel Müller Nov 01 '13 at 15:28
  • 7
    @MichelMüller when building an image from a dockerfile you can specify the `-rm` option to remove intermediate containers after a successful build. – Freek Kalter Nov 13 '13 at 20:30
  • @FreekKalter Interesting - but doesn't that mean that the containers are getting removed that the building process is using for caching? In that case it does exactly the opposite of what I want - I want to remove containers that no running container or tagged image is building upon, such that if I rerun the build it won't start from the beginning, yet I'm not constantly keeping intermediate steps that led to nowhere. – Michel Müller Nov 13 '13 at 21:13
  • 4
    @MichelMüller the images are what are used for caching, so removing the containers won't effect that. – Ken Cochrane Nov 13 '13 at 21:34
  • 7
    If you want to use awk for this consider this command if you want do rm all stopped containers (without a error because of the first line): `docker ps -a | awk 'NR > 1 {print $1}' | xargs docker rm` – omni Jun 15 '14 at 14:45
  • Based on this comment id made a cleanup script to delete old containers of different ages. You can get it here:https://github.com/juanluisbaptiste/docker-utils/blob/master/scripts/docker_cleanup.sh – Juancho Jul 08 '14 at 06:23
  • 2
    If you get permission denied errors, add `sudo` before docker on the last command: `$ sudo docker ps -a | grep 'weeks ago' | awk '{print $1}' | xargs --no-run-if-empty sudo docker rm -f` – Luciano Bargmann Nov 12 '14 at 17:33
  • If there is a lot of containers/images you can use ```docker ps -aq | tr '\n' ' ' | xargs --no-run-if-empty docker rm```. The output passed to docker rm will be merged into one line so only one docker command will be executed. It's a little speed up. – spinus Jan 07 '15 at 02:50
  • 1
    I am using Mac OS 10 Yosemites and this solution doesn't seems to be working (even if I added sudo before the command). – Shih-Min Lee Mar 19 '15 at 04:26
  • 2
    It is worth to note that you can replace `grep … | awk` by just `awk`. – Michaël Le Barbier Apr 16 '15 at 08:29
  • 1
    You should rather use: `docker ps -a --no-trunc | egrep '((weeks)|(months)) ago' | awk '{print $1}' | xargs --no-run-if-empty docker rm`. It also removes containers that are months old (docker uses months after 12 weeks). It also avoids ambiguity. – Matt3o12 May 25 '15 at 16:25
  • This command intertwines mechanism and policy. Why should a weeks old image be removed while it's possibly still relevant. Furthermore, this command relies on scraping. using the "-aq" options is more future proof. – hbogert Nov 15 '15 at 15:55
  • 3
    This should be the updated command for removing untagged images `docker rmi $(docker images -q -f dangling=true)` – Ghjnut Nov 17 '15 at 17:19
  • @Ghjnut yours was the only one that finally worked for me on Mac, though I had to change it a little. `docker rmi $(docker images -a -q)` all the others that I tried refused to do anything, giving a message about 'dependant child images'. Whoever decides to run this, watch out because it removes absolutely everything. – mwarren Nov 20 '15 at 14:03
  • DANGEROUS!!!! USE IT WITH CAUTION! Due to the grep as second command, it will also return you lines where it says "created X weeks ago", so you could potentially end up deleting recently created containers! – SKR Oct 13 '16 at 14:42
  • Doesn't work on OSX get `xargs: illegal option -- -`. The question doesn't specify Linux, so going with Ryan Walls answer below as it's more concise and works cross platform (linux and osx). – Ray Feb 24 '17 at 16:28
  • 1
    You should really just use docker container prune, should work on all platforms. – Ken Cochrane Feb 24 '17 at 16:30
  • With the very latest Docker, use `docker container prune`. If you can't use the latest Docker, say if you are using the latest Minikube v0.21 which doesn't have the very latest Docker, use the simpler `docker rm $(docker ps -q --filter "status=exited")` – clay Aug 29 '17 at 17:21
  • There's a much simpler way, as long as you can calculate the number of hours: 1 week: 168 hours `docker container prune -f --filter "until=168h"` – Jeramy Rutley Apr 29 '20 at 20:21
636

Another method, which I got from Guillaume J. Charmes (credit where it is due):

docker rm `docker ps --no-trunc -aq`

will remove all containers in an elegant way.

And by Bartosz Bilicki, for Windows:

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

For PowerShell:

docker rm @(docker ps -aq)

An update with Docker 1.13 (Q4 2016), credit to VonC (later in this thread):

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
Community
  • 1
  • 1
qkrijger
  • 24,730
  • 6
  • 32
  • 37
  • 11
    this somehow doesnt work for me, but `docker ps -a -q | xargs docker rm` works, (sudo may be needed) – FUD Jan 09 '14 at 09:29
  • 87
    what about `docker rm $(docker ps -a -q)` ? – qkrijger Jan 09 '14 at 20:48
  • 8
    @qkrijger, this doesn't change anything from your original answer, except for adding bashism. The problem is with command line overflow. xargs variant deals with it in a nice way. I would also add --no-trunk to docker ps to avoid (unlikely) id clashes. – Ihor Kaharlichenko Feb 07 '14 at 22:32
  • @IhorKaharlichenko You are right, thanks for the elaboration. Also, good idea on the notrunc option. I updated the answer with it and will update my scripts as well ☺ – qkrijger Feb 09 '14 at 00:08
  • @chuwy My docker installation 0.7.x has `-notrunc` – qkrijger Feb 10 '14 at 10:22
  • @qkrijger hm, that's right. They using -notrunc for <0.8 http://docs.docker.io/en/v0.7.3/commandline/cli/#ps and --no-trunc for 0.8 http://docs.docker.io/en/latest/reference/commandline/cli/#ps And I didn't find any mentions about this in CHANGELOG. – chuwy Feb 10 '14 at 16:02
  • 8
    be aware if you use data-only container, it will remove them also – Dzung Nguyen Mar 26 '14 at 12:08
  • @FUD like your command and add `-f` to force if needed, then it is `docker ps -a -q | xargs docker rm -f` – Larry Cai May 31 '14 at 02:47
  • 4
    I don't see the point with `--no-trunc` since `docker rm` doesn't need full IDs anyway. – Pithikos Aug 08 '14 at 09:44
  • 3
    @Pithikos the point is the very slim chance that two hashes start with the same 8 alphanumerical characters :). The point is that there is no point in not using the whole hash when you script anyway – qkrijger Aug 08 '14 at 15:37
  • I used to remove old images with the chosen answer, but for some reason couldn't (docker rmi erred with some weird tag, different than passed). Then I've used this command - it did "something", possibly removed dangling images? Anyway it fixed the first command - which effectively cleared my images repo ;) – hauron Sep 29 '14 at 11:30
  • Why docker doesn't have normal inertial command for this? like: `docker rm --all --force` or `docker rm-all-containers`? – sobi3ch Nov 14 '14 at 11:41
  • I've tried many things, and this is the only one that worked for me – Ashley Coolman Dec 27 '14 at 17:45
  • This worked for me on Win 8.1 with boot2docker. I probably wouldn't like to run it with any real containers setup, I just wanted to clear out the testing stuff I'd created. – Kioshiki May 30 '15 at 09:44
  • @IhorKaharlichenko, I am all for `xargs` - but still, no bashism was added in qkrijger's comment - or do you consider `$()` as bashism? – maxschlepzig Apr 06 '16 at 06:42
  • 2
    @maxschlepzig, I don't remember what exactly I was thinking when writing that comment, so let's consider it a mistake. By no means `$()` is a bashism, moreover IIRC backticks are considered deprecated and `$()` are the recommended way to go. – Ihor Kaharlichenko Apr 06 '16 at 10:52
  • 1
    PowerShell version: docker ps -aq --no-trunc | %{docker rm $_} – Joe Niland Nov 14 '16 at 22:41
  • From this post (https://gist.github.com/ngpestelos/4fc2e31e19f86b9cf10b): Power Shell option &'C:\Program Files\Docker\docker' ps -a | foreach-object { $l = $PSItem.ToString(); $c = $l.Substring(0, $l.IndexOf(" ")); if ($c.ToLower() -ne "container") { $cmd = "c:\Program Files\Docker\docker.exe"; & $cmd "rm" $c } } – evgenyl Jan 04 '17 at 07:23
  • just saved me `13gb` – Christian Bongiorno Nov 03 '17 at 22:55
  • docker rm $(docker ps -a -q) fails if there is no contatiners to delete – Lobo May 21 '18 at 13:06
416

Updated Answer Use docker system prune or docker container prune now. See VonC's updated answer.

Previous Answer Composing several different hints above, the most elegant way to remove all non-running containers seems to be:

docker rm $(docker ps -q -f status=exited)

  • -q prints just the container ids (without column headers)
  • -f allows you to filter your list of printed containers (in this case we are filtering to only show exited containers)
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Ryan Walls
  • 6,662
  • 1
  • 33
  • 41
  • 7
    This should be the correct answer because it relies on docker to tell you which containers are no longer used, rather than assuming the text output format of $(docker images) will not change. Bonus points for spawning only one extra process instead of two. – eurythmia Aug 26 '15 at 11:43
  • 18
    You might want to add `-v` to avoid dangling volumes: `docker rm -v $(docker ps -q -f status=exited)`. See https://docs.docker.com/userguide/dockervolumes/#creating-and-mounting-a-data-volume-container for details about dangling volumes. – rluba Oct 16 '15 at 13:19
  • @rluba apparently in Docker 1.9 there will be a separate volume api for handling that problem. https://github.com/docker/docker/pull/14242 – Ryan Walls Oct 16 '15 at 16:47
  • an alias might be handy: `alias docker-gc="docker rm -v \$(docker ps -q -f status=exited)"` – Frank Neblung Jul 15 '16 at 09:36
  • Unlike the answer marked correct, @RyanWalls answer works on OSX as well as being more concise. – Ray Feb 24 '17 at 16:31
  • "docker rm" requires at least 1 argument(s). – Xero Sep 26 '17 at 07:44
258

The official way is:

docker rm `docker ps -aq`

The Docker maintainers have indicated there will be no command for this - and you compose the commands like that:

We have discussed this before and prefer users to use the above line without having to add additional code to Docker.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Michael Neale
  • 18,590
  • 18
  • 72
  • 106
  • 6
    This is a bad solution though, because it'll also delete storage containers. – Sobrique Jan 10 '16 at 16:39
  • 8
    What do you mean "storage containers"? If you mean data-only containers which once upon a time were used to keep references to data volumes, those are no longer necessary because of the availability of `docker volume` subcommand, and named volumes. – L0j1k Apr 01 '16 at 23:52
  • Note that this won't work inside Windows Powershell. For that, this is a better solution: https://stackoverflow.com/a/23674294/1150683 – Bram Vanroy Jan 30 '18 at 09:53
  • @Sobrique If you don't react, at least you should delete your comment, it is nearly complete and harmful nonsense. – peterh Feb 25 '18 at 16:22
129

With Docker 1.13 (Q4 2016), you now have:

docker system prune -a will delete ALL unused data (i.e., in order: containers stopped, volumes without containers and images with no containers).

docker system prune without -a will remove (for images) only dangling images, or images without a tag, as commented by smilebomb.

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 -a

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

As wjv comments,

There is also docker {container,image,volume,network} prune, which may be used to remove unused instances of just one type of object.

Introduced in commit 913e5cb, only for Docker 1.13+.

docker container prune
VonC
  • 1,042,979
  • 435
  • 3,649
  • 4,283
105

It is now possible to use filtering with docker ps:

docker rm $(docker ps -q -f status=exited)

And for images:

docker rmi $(docker images -q -f "dangling=true")

However, any of those will cause docker rm or docker rmi to throw an error when there are no matching containers. The older docker rm $(docker ps -aq) trick was even worse as it tried to remove any running container, failing at each one.

Here's a cleaner script to add in your ~/.bashrc or ~/.profile :

# Use `docker-cleanup --dry-run` to see what would be deleted.

function docker-cleanup {
  EXITED=$(docker ps -q -f status=exited)
  DANGLING=$(docker images -q -f "dangling=true")

  if [ "$1" == "--dry-run" ]; then
    echo "==> Would stop containers:"
    echo $EXITED
    echo "==> And images:"
    echo $DANGLING
  else
    if [ -n "$EXITED" ]; then
      docker rm $EXITED
    else
      echo "No containers to remove."
    fi
    if [ -n "$DANGLING" ]; then
      docker rmi $DANGLING
    else
      echo "No images to remove."
    fi
  fi
}

Edit: As noted below, original answer was for removing images, not containers. Updated to answer both, including new links to documentation. Thanks to Adrian (and Ryan's answer) for mentioning the new ps filtering.

caktux
  • 4,017
  • 2
  • 15
  • 10
101

UPDATED 2021 (NEWEST)

docker container prune

This - 2017 (OLD) way

To remove ALL STOPPED CONTAINERS

docker rm $(docker ps -a -q)

To remove ALL CONTAINERS (STOPPED AND NON STOPPED)

docker rm  -f $(docker ps -a -q)
levi
  • 19,165
  • 7
  • 56
  • 68
  • 3
    downvoted, since this is for sure _not_ the way you do that in 2017 - whis would be `docker volume/container/image prune`, see https://stackoverflow.com/a/39860665/3625317 – Eugen Mayer Jun 25 '17 at 11:00
  • 8
    upvoted to counter the downvote because a) this answer was from 2016, and b) plenty of folks dont run the bleeding edge. – keen Oct 02 '17 at 20:58
50

Remove all stopped containers:

docker rm $(docker ps -a | grep Exited | awk '{print $1}')

From the comment by pauk960:

Since version 1.3.0 you can use filters with docker ps, instead of grep Exited use docker ps -a -f status=exited. And if you use -q with it you can get container IDs only instead of full output, no need to use awk for that.

Community
  • 1
  • 1
Montells
  • 5,513
  • 3
  • 41
  • 48
35

If you do not like to remove all containers, you can select all containers created before or after a specific container with docker ps -f before=<container-ID> or with docker ps -f since=<container-ID>

Let's say you have developed your system, and now it is working, but there are a number of containers left. You want to remove containers created before that working version. Determine the ID of the working container with docker ps.

Remove containers created before an other container

docker rm $(docker ps -f before=9c49c11c8d21 -q)

Another example. You have your database already running on a Docker container. You have developed your application to run on another container and now you have a number of unneeded containers.

Remove containers created after a certain container

docker rm $(docker ps -f since=a6ca4661ec7f -q)

Docker stores containers in /var/lib/docker/containers in Ubuntu. I think extra containers do no other harm, but take up disk space.

Konstantin Pereiaslov
  • 1,621
  • 1
  • 18
  • 26
vesako
  • 1,738
  • 1
  • 11
  • 7
32

Update: As of Docker version 1.13 (released January 2017), you can issue the following command to clean up stopped containers, unused volumes, dangling images and unused networks:

docker system prune

If you want to insure that you're only deleting containers which have an exited status, use this:

docker ps -aq -f status=exited | xargs docker rm

Similarly, if you're cleaning up docker stuff, you can get rid of untagged, unnamed images in this way:

docker images -q --no-trunc -f dangling=true | xargs docker rmi
L0j1k
  • 10,933
  • 7
  • 48
  • 64
22

Here is my docker-cleanup script, which removes untagged containers and images. Please check the source for any updates.

#!/bin/sh
# Cleanup docker files: untagged containers and images.
#
# Use `docker-cleanup -n` for a dry run to see what would be deleted.

untagged_containers() {
  # Print containers using untagged images: $1 is used with awk's print: 0=line, 1=column 1.
  docker ps -a | awk '$2 ~ "[0-9a-f]{12}" {print $'$1'}'
}

untagged_images() {
  # Print untagged images: $1 is used with awk's print: 0=line, 3=column 3.
  # NOTE: intermediate images (via -a) seem to only cause
  # "Error: Conflict, foobarid wasn't deleted" messages.
  # Might be useful sometimes when Docker messed things up?!
  # docker images -a | awk '$1 == "<none>" {print $'$1'}'
  docker images | tail -n +2 | awk '$1 == "<none>" {print $'$1'}'
}

# Dry-run.
if [ "$1" = "-n" ]; then
  echo "=== Containers with uncommitted images: ==="
  untagged_containers 0
  echo

  echo "=== Uncommitted images: ==="
  untagged_images 0

  exit
fi

# Remove containers with untagged images.
echo "Removing containers:" >&2
untagged_containers 1 | xargs --no-run-if-empty docker rm --volumes=true

# Remove untagged images
echo "Removing images:" >&2
untagged_images 3 | xargs --no-run-if-empty docker rmi

Source: https://github.com/blueyed/dotfiles/blob/master/usr/bin/docker-cleanup

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
blueyed
  • 24,971
  • 4
  • 72
  • 70
  • @BradMurray Thanks! You might also like these: https://github.com/blueyed/dotfiles/commit/12591ec823d408997819b354c7dc4ac3dfeb88eb – blueyed Jun 07 '14 at 23:06
  • 3
    Does not work on OSX because of the `xargs --no-run-if-empty` option – caktux Jul 14 '15 at 05:36
14

First, stop running containers before attempting to remove them

Remove running containers

docker rm $(docker stop -t=1 $(docker ps -q))

You could use kill instead of stop. In my case I prefer stop since I tend to rerun them vs. creating a new one every time so I try to shut them down nicely.

Note: Trying to stop a container will give you an error:

Error: Impossible to remove a running container, please stop it first

Remove all containers

docker rm $(docker ps -a -q)
Community
  • 1
  • 1
Ulises
  • 12,931
  • 5
  • 31
  • 48
11

Removing all containers from Windows shell:

FOR /f "tokens=*" %i IN ('docker ps -a -q') DO docker rm %i
Bartosz Bilicki
  • 10,502
  • 8
  • 63
  • 98
10

https://github.com/HardySimpson/docker-cleanup

Docker cleanup

A tiny all-in-one shell, which removes:

  • Containers that not running more than one day ago
  • Images that don't belong to any remaining container

Intend to run as a crontab job

Feature

  • It will remove all <none>:<none> images
  • If the image has multiple repo:tag references to it, it will remove all repo:tag except with running a container. Actually it is a nature of "docker rmi".
  • Many error message will be show on screen, and you can decide to 2>/dev/null or not
  • Learn something from docker-gc, and fix its problem (it can not remove image that has mutliple repo:tag)
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
HardySimpson
  • 1,006
  • 1
  • 11
  • 14
9

So, personally I recommend doing this as part of your deploy script for both images and containers, keeping only the most recent n containers and images. I tag my Docker images with the same versioning schema I use with git tag as well as always tagging the latest Docker image with "latest." This means that without cleaning up anything, my Docker images wind up looking like:

REPOSITORY              TAG       IMAGE ID        CREATED         VIRTUAL SIZE
some_repo/some_image    0.0.5     8f1a7c7ba93c    23 hours ago    925.4 MB
some_repo/some_image    latest    8f1a7c7ba93c    23 hours ago    925.4 MB
some_repo/some_image    0.0.4     0beabfa514ea    45 hours ago    925.4 MB
some_repo/some_image    0.0.3     54302cd10bf2    6 days ago      978.5 MB
some_repo/some_image    0.0.2     0078b30f3d9a    7 days ago      978.5 MB
some_repo/some_image    0.0.1     sdfgdf0f3d9a    8 days ago      938.5 MB

Now, of course I don't want to keep all my images (or containers) going back to perpetuity on all my production boxes. I just want the last 3 or 4 for rollbacks and to get rid of everything else. Unix's tail is your best friend here. Since docker images and docker ps both order by date, we can just use tail to select all but the top three and remove them:

docker rmi $(docker images -q | tail -n +4)

Run that along with your deploy scripts (or locally) to always keep just enough images to comfortably roll back without taking up too much room or cluttering stuff up with old images.

Personally, I only keep one container on my production box at any time, but you can do the same sort of thing with containers if you want more:

docker rm $(docker ps -aq | tail -n +4)

Finally, in my simplified example we're only dealing with one repository at a time, but if you had more, you can just get a bit more sophisticated with the same idea. Say I just want to keep the last three images from some_repo/some_image. I can just mix in grep and awk and be on my way:

docker rmi $(docker images -a | grep 'some_repo/some_image' | awk '{print $3}' | tail -n +4)

Again, the same idea applies to containers, but you get it by this point so I'll stop giving examples.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Eli
  • 31,424
  • 32
  • 127
  • 194
8

Use:

docker rm -f $(docker ps -a -q)

It forcefully stops and removes all containers present locally.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Shashank G
  • 646
  • 1
  • 11
  • 24
  • Please edit with more information. Code-only and "try this" answers are discouraged, because they contain no searchable content, and don't explain why someone should "try this". We make an effort here to be a resource for knowledge. – Brian Tompsett - 汤莱恩 Sep 07 '16 at 14:25
  • In ubuntu 16.04, docker requires sudo, so you have to write `sudo docker rm -f $(sudo docker ps -a -q)`. – Elliott Sep 21 '16 at 15:47
  • as a plus, this also works in Windows under powershell! – Robert Ivanc Oct 21 '16 at 14:34
  • @Elliott I think `sudo` is required everywhere unless you add your user to the 'docker' group. I use ubuntu 16.10 without sudo by adding my user to the docker group. – emory Mar 26 '17 at 11:38
7

Remove 5 oldest containers:

docker rm `docker ps -aq | tail -n 5`

See how many containers there are left:

docker ps -aq | wc -l
Pithikos
  • 14,773
  • 14
  • 98
  • 115
7

Remove all stopped containers.

sudo docker rm $(sudo docker ps -a -q)

This will remove all stopped containers by getting a list of all containers with docker ps -a -q and passing their ids to docker rm. This should not remove any running containers, and it will tell you it can’t remove a running image.

Remove all untagged images

Now you want to clean up old images to save some space.

sudo docker rmi $(sudo docker images -q --filter "dangling=true")

Ric_Harvey
  • 91
  • 1
  • 7
  • Don't forget to delete docker volumes by specifying the -v option (sudo docker rm -v $(sudo docker ps -a -q)) – vcarel Nov 09 '15 at 10:30
  • Didn't look this up, but I guess the same as: `docker ps -aq | xargs docker rm -v` – quine Mar 23 '18 at 20:24
  • This only works on Linux, not Windows... But `docker rm -f $(docker ps -a -q)` works in PowerShell / Docker for Windows. – Peter Mortensen Jul 24 '18 at 07:58
6
  1. Remove all docker processes:

    docker rm $(docker ps -a -q)
    
  2. Remove specific container:

    $ docker ps -a (lists all old containers)
    
    $ docker rm container-Id
    
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
padakpadak
  • 101
  • 2
  • 5
6

New way: spotify/docker-gc play the trick.

 docker run --rm -v /var/run/docker.sock:/var/run/docker.sock -v /etc:/etc spotify/docker-gc
  • Containers that exited more than an hour ago are removed.
  • Images that don't belong to any remaining container after that are removed

It has supported environmental settings

Forcing deletion of images that have multiple tags

 FORCE_IMAGE_REMOVAL=1

Forcing deletion of containers

 FORCE_CONTAINER_REMOVAL=1 

Excluding Recently Exited Containers and Images From Garbage Collection

 GRACE_PERIOD_SECONDS=86400

This setting also prevents the removal of images that have been created less than GRACE_PERIOD_SECONDS seconds ago.

Dry run

 DRY_RUN=1

Cleaning up orphaned container volumes CLEAN_UP_VOLUMES=1

Reference: docker-gc

Old way to do:

delete old, non-running containers

 docker ps -a -q -f status=exited | xargs --no-run-if-empty docker rm
             OR 
 docker rm $(docker ps -a -q)

delete all images associated with non-running docker containers

 docker images -q | xargs --no-run-if-empty docker rmi

cleanup orphaned docker volumes for docker version 1.10.x and above

 docker volume ls -qf dangling=true | xargs -r docker volume rm

Based on time period

 docker ps -a | grep "weeks ago" | awk "{print $1}" | xargs --no-run-if-empty docker rm
 docker ps -a | grep "days ago" | awk "{print $1}" | xargs --no-run-if-empty docker rm
 docker ps -a | grep "hours ago" | awk "{print $1}" | xargs --no-run-if-empty docker rm
f-society
  • 2,418
  • 21
  • 18
5

You can use the following command to remove the exited containers:

docker rm $(sudo docker ps -a | grep Exit | cut -d ' ' -f 1)

Here is the full gist to also remove the old images on docker: Gist to remove old Docker containers and images.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
urodoz
  • 51
  • 2
  • 1
4
#!/bin/bash
# docker-gc --- Remove stopped docker containers

RUNNING=$(docker ps -q)
ALL=$(docker ps -a -q)

for container in $ALL ; do
    [[ "$RUNNING" =~ "$container" ]] && continue
    echo Removing container: $(docker rm $container)
done
mckoss
  • 6,235
  • 5
  • 28
  • 28
4

You can remove only stopped containers. Stop all of them in the beginning

docker stop $(docker ps -a -q)

Then you can remove

docker rm $(docker ps -a -q)

Marcin Szymczak
  • 9,665
  • 4
  • 48
  • 60
3

I always use docker rmi $(docker ps -a -q) to remove all images.

You can remove directory /var/lib/docker/graph when docker rmi failed.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
sunny
  • 39
  • 2
3

The basic steps to stop/remove all containers and images

  1. List all the containers

    docker ps -aq

  2. Stop all running containers

    docker stop $(docker ps -aq)

  3. Remove all containers

    docker rm $(docker ps -aq)

  4. Remove all images

    docker rmi $(docker images -q)

Note: First you have to stop all the running containers before you remove them. Also before removing an image, you have to stop and remove its dependent container(s).

Community
  • 1
  • 1
3

Try this command to clean containers and dangling images.

docker system prune -a
Pal
  • 712
  • 5
  • 6
2

Remove all containers created from a certain image:

docker rm  $(docker ps -a | awk '/myimage:mytag/{print $1}')
Community
  • 1
  • 1
estani
  • 17,829
  • 2
  • 74
  • 52
2

On Ubuntu 14.04 (Trusty Tahr):

$ for CON in `docker ps -qa`; do docker rm $CON ; done

This is just a normal Bash command so it should work with EVERY Bash-compliant terminal.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
sobi3ch
  • 1,928
  • 2
  • 23
  • 37
2

To remove ALL containers:

sudo docker ps -a | grep -v CONTAINER | awk '{print $1}' | xargs --no-run-if-empty sudo docker rm -f

Explanation:

sudo docker ps -a

Returns a list of containers.

awk '{print $1}'

Gets the first column which is the container ID.

grep -v CONTAINER

Remove the title.

The last pipe sends the IDs to sudo docker rm -f safely.

Felipe
  • 15,458
  • 9
  • 63
  • 87
  • Wow. For a newbie user like me, that sounds a little bit complicated. Would you please add some instruction about what it has done and the pipelines. I would be thankful if you could check [my answer](https://stackoverflow.com/a/58068287/7310077), too. – Mostafa Ghadimi Sep 23 '19 at 18:44
  • I added an explanation. – Felipe Sep 26 '19 at 14:41
2

For anyone interested, I took the example from qkrijger and turned it into a clear all (stop and remove all)

docker stop `docker ps --no-trunc -aq` ; docker rm `docker ps --no-trunc -aq`
Kraig McConaghy
  • 248
  • 4
  • 4
  • If you are removing the containers anyway, then `docker rm -f $(docker ps --no-trunc -aq)` is faster – qkrijger Apr 10 '15 at 07:50
  • True, but if you need it to go through proper shutdown to cleanup shared or reused resources (i.e. Attached volumes, correctly closed active connections, etc) then you need to call stop first. Great example, if you have a Jenkins container, then killing the container is a bad idea. You want it to save any unpersisted changes, warn logged in users, and, very importantly, properly stop all builds. – Kraig McConaghy Apr 10 '15 at 12:57
  • agreed, that is a very valid use case – qkrijger Apr 26 '15 at 22:55
2

To simply remove everything that is not currently used by a running container the following alias, that I usually put into the .bash_profile on my Mac, will help:

alias dockerclean="docker ps -q -a | xargs docker rm -v && docker images -q | xargs docker rmi"

Whenever dockerclean is invoked from the command line it will remove stopped containers as well as unused image layers. For running containers and used images it will print a warning message and skip over it.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
0x7d7b
  • 41,374
  • 7
  • 39
  • 55
2
#!/bin/bash

echo Cleanup unused containers
unused_containers=$(docker ps -a -q --filter="status=exited")
if [[ -n $unused_containers ]]
then
  docker rm $unused_containers
fi

echo Cleanup unused images
unused_images=$(docker images | grep '^<none>' | awk '{print $3}')
if [[ -n $unused_images ]]
then
  docker rmi $unused_images
fi
AleX
  • 121
  • 1
  • 2
  • 5
    When you are answering, it's best to have some explanation as to what the solution does rather than just a code dump, as otherwise the answer may be deleted. – AlBlue May 19 '16 at 09:44
2
docker rm --force `docker ps -qa`
Sivalingam
  • 711
  • 9
  • 16
2

I'm using:

docker rm -v $(docker ps -a -q -f status=exited)

to delete exited containers and:

docker rmi -f $(docker images | grep "<none>" | awk "{print \$3}")

in order to get rid of all untagged images.

Alexandru Bantiuc
  • 3,007
  • 2
  • 8
  • 6
2

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 in 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 by default (or however long you set it using DELAY_TIME=1800 option) and clean up exited containers and images.

More details: Docker Cleanup

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

Here is a script to remove both running and exited containers created longer than 2 days:

#!/bin/bash
# This script will kill and remove containers older than 2 days.
#
docker ps -aq > /scripts/containers.txt
today=`date +%Y-%m-%d`
oldate=`date --date="2 day ago" +%Y-%m-%d`
while read p; do
    cont=`docker inspect -f '{{ .Created }}' $p | cut -c 1-10`
    echo " Created date of $p is $cont"
    k=`echo $(( ( $(date -ud $today +'%s') - $(date -ud $cont +'%s'))/60/60/24 ))`
    echo $k
    if [ $k -ge 2 ];
    then
            echo "Killing docker container $p"
            docker kill $p
            echo "Removing docker container $p"
            docker rm $p
    else
            echo "Docker container $p is not one day old, so keeping the container."
    fi
done </scripts/containers.txt
ZenithS
  • 824
  • 6
  • 17
SAB
  • 267
  • 2
  • 9
2

This process contains two steps (stop and remove):

  1. Stop the container that is being used by any running microservices

    docker stop $(docker ps -a -q)
    
  2. Remove all the containers

    docker rm $(docker ps -a -q)
    
  3. Remove single container

    docker rm container-ID
    
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
2

I found the below command is very handy to stop and remove all the containers. You don't need to stop explicitly with another command if you are using the -f (force) flag as it stops all running containers:

docker rm -f $(docker ps -a -q)
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Pinaki Mukherjee
  • 1,326
  • 2
  • 17
  • 29
2

Use the following nested commands:

$ sudo docker stop $(sudo docker ps -a -q)

This command stops all running containers.

$ sudo docker rm $(sudo docker ps -a -q)

This command remove all containers.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Rahul Bagad
  • 87
  • 2
  • 7
2

To remove ALL stopped docker containers, run:-

$ docker container prune

You'll have to be careful with this command since it removes all stopped containers indiscriminately so make sure there's no stopped/currently unused container that you may still have use of.

A more precise alternative is to remove the container by ID. You'll have to first list the stopped containers using this command:-

docker ps --filter "status=exited"

You'll then copy the ID of the container you want to remove. Thereafter, execute the following command that removes a single container,

docker container rm <container ID>

or the one below to remove multiple containers at once by running:-

docker container rm <container ID 1> <container ID 2> <container ID n>
pickup limes
  • 345
  • 2
  • 7
1

I use variations of the following:

docker ps -a | grep 'cassandra.*Exited' | cut -d " " -f 1

The first part lists all processes.

The second selects just those that have 'cassandra' followed by 'Exited'.

The third, removes all the tests after the image ID, so you get a list of image ids.

So,

docker rm $(docker ps -a | grep 'cassandra.*Exited' | cut -d " " -f 1)
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
JRun
  • 3,178
  • 5
  • 22
  • 39
1

For a Linux installation make sure you use sudo. Also it's good to look for images that are months and weeks old:

sudo docker ps -a | grep 'weeks ago\|months ago' | \
    awk '{print $1}' | xargs --no-run-if-empty sudo docker rm
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Paul Oliver
  • 7,009
  • 5
  • 28
  • 33
1

You can use docker-helper from the repository https://github.com/kartoza/docker-helpers. After the install, just type drmc.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
etrimaille
  • 221
  • 1
  • 3
  • 12
1

These two lines of Bash will filter containers by some keywords before deleting them:

containers_to_keep=$(docker ps -a | grep 'keep\|Up\|registry:latest\|nexus' | awk '{ print $1 }')
containers_to_delete=$(docker ps -a | grep Exited | grep -Fv "$containers_to_keep" | awk '{ print $1 }')
docker rm $containers_to_delete

From this post.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Emil Salageanu
  • 847
  • 1
  • 9
  • 23
1

This short script might help (compiled from previous answers)!

#!/bin/bash

# Remove dangling images

IMAGE_IDS=$(sudo docker images -f "dangling=true" -q)

if [ -n "$IMAGE_IDS" ]; then

    sudo docker rmi $IMAGE_IDS > /dev/null 2>&1
    echo 'Images removed' $IMAGE_IDS
fi


# Remove exited containers

CONTAINER_IDS=$(sudo docker ps -a -q -f status=exited)

if [ -n "$CONTAINER_IDS" ]; then

    sudo docker rm -v $CONTAINER_IDS > /dev/null 2>&1
    echo 'Containers remove $CONTAINER_IDS'
fi
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Chetan Sharma
  • 173
  • 1
  • 2
  • 16
1

From my experience, you should stop containers before removing them to avoid things like "this container is still running" kind of errors, so:

sudo /usr/bin/docker ps -aq |  awk '{print $1}' | \
xargs --no-run-if-empty bash -c 'sudo docker stop $@; sudo docker rm $@' bash

I keep an alias in my dotfiles like:

alias wipedocker="sudo /usr/bin/docker ps -aq |  awk '{print $1}' \
| xargs --no-run-if-empty bash -c 'sudo docker stop $@; sudo docker rm $@' bash"
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
CESCO
  • 5,396
  • 4
  • 41
  • 73
1

docker rm -f $(docker ps -a -q) will do the trick. It will stop the containers and remove them too.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Jagatveer Singh
  • 185
  • 2
  • 12
1

Removing older Docker containers is very easy.

List all the containers:

docker ps -a
docker ps (To list the running containers)

Once you hit docker ps -a, it will give you list of containers along with the container id (which is unique and combination of a-z, A-Z and 0-9). Copy the container id you wanted to remove and simply hit the below.

docker rm container_id

Your container will be removed along with the layers created in /var/lib/docker/aufs (if you are using Ubuntu).

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

Here is a one-liner that removes all the exited containers.

docker rm $(docker ps -a | grep Exited | grep -v CON | awk '{print $1}')

If you want to remove ALL the images you can use something like this.

docker rmi $(docker images | sed -n '1!p' | awk '{print $3}')

nPcomp
  • 5,621
  • 1
  • 37
  • 45
1

To delete a specify container

docker container rm container_id

If the container is running, you have to stop it before to delete it

docker container stop container_id

And this command is to delete all existing containers

docker container rm $(docker container -a -q)
giapnh
  • 1,554
  • 16
  • 17
1

Use the docker management tool Portainer

We can manage all the old containers, non using volumes and images by using this tool

Its a simple management UI for dockers

HOW TO DEPLOY PORTAINER

Use the following Docker commands to deploy Portainer:

$ docker volume create portainer_data
$ docker run -d -p 9000:9000 -v /var/run/docker.sock:/var/run/docker.sock -v portainer_data:/data portainer/portainer

You'll just need to access the port 9000 of the Docker engine where portainer is running using your browser.

Note: the -v /var/run/docker.sock:/var/run/docker.sock option can be used in Linux environments only.

Corey
  • 977
  • 3
  • 17
  • 28
Anish Varghese
  • 2,737
  • 3
  • 10
  • 21
1

I am using following commands to delete Exited and Restarting docker containers

docker stop --force $(docker ps -a|grep Exited| awk '{print $1}')
docker rm --force $(docker ps -a|grep Exited| awk '{print $1}')
docker stop --force $(docker ps -a|grep Restarting| awk '{print $1}')
docker rm --force $(docker ps -a|grep Restarting| awk '{print $1}')

Using below command to remove images named as none

docker image rm --force $(docker image ls  |grep none |awk '{print $3}')
Sijo M Cyril
  • 422
  • 5
  • 10
1

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)
Vikram Biwal
  • 1,940
  • 1
  • 21
  • 30
1

To get rid of your stopped container you can use:

docker rm <cointainer_id>

You can also use the name of the container:

docker rm <name>

If you want to get rid of all the stopped containers you can use the:

docker container prune

Or you can also use:

docker rm $(docker ps -aq -f status=exited)

You can use -v argument to delete any docker managed volumes that are not referenced any further

docker rm -v $(docker ps -aq -f status=exited)

You can also use --rm with the docker run. This will delete the container and the associated files when the container exists.

Karan Khanna
  • 1,407
  • 2
  • 13
  • 40
1

You can remove the containers using multiple ways that I will explain them in the rest of the answer.

  1. docker container prune. This command removes the all of the containers that are not working right now. You can find out which containers are not working by comparing the output of docker ps and docker ps -a. The containers that are listed in docker ps -a and not exist in docker ps are not working right now, but their containers aren't removed.

  2. docker kill $(docker ps -aq). What this command does is that by executing $(docker ps -aq) it returns the list of ids of all containers and kill them. Sometime this command doesn't work because it is being using by the running container. To make that work, you can use --force option.

  3. docker rm $(docker ps -aq). It has the same definition as the second command. The only difference of them is that it removes the container (as same as docker prune), while the docker kill doesn't.

  4. Sometimes it is needed to remove the image, because you have changed the configuration of the Dockerfile and need to remove it to rebuild it. For this purpose you can see all of the images by running docker images and then copy the ID of the image that you want to remove. It can be deleted simply by executing docker image rm <image-id>.

PS: You can use docker ps -a -q instead of docker ps -aq and there is no differences. Because in unix-based operating system, you can join the options like the above example.

Mostafa Ghadimi
  • 2,753
  • 4
  • 29
  • 63
1

If you want to remove all containers then use

docker container prune

This command will remove all containers

Why not clean whole docker system with

docker system prune

Slim Coder
  • 844
  • 5
  • 14
1

For Windows you can run this to stop and delete all containers:

@echo off
FOR /f "tokens=*" %%i IN ('docker ps -q') DO docker stop %%i
FOR /f "tokens=*" %%i IN ('docker ps -aq') DO docker rm %%i
FOR /f "tokens=*" %%i IN ('docker images --format "{{.ID}}"') DO docker rmi %%i

You can save it as a .bat file and can run to do that:

enter image description here

Raghav
  • 6,381
  • 4
  • 60
  • 85
0

On windows (powershell) you could do something like this:

  1. $containers = docker ps -a -q
  2. foreach ($container in $containers) {docker rm $container -f }
LeYAUable
  • 778
  • 7
  • 19
0

I wanted to add this simple answer as I didn't see it, and the question is specifically "old" not "all".

sudo docker container prune --filter "until=24h"

Adjust the 24h for whatever time span you want to remove containers that are older than.

edencorbin
  • 1,915
  • 3
  • 21
  • 37
-1

You can use some of the Docker UI applications to remove containers.

Sorry for advertisement, but I always use my own application to do the same things. You can try it if you are looking for a simple application to manage Docker images or containers: https://github.com/alex-agency/AMHub.

This is a Docker UI web application which is running inside a Docker container. For installing it, you only need invoke this command:

docker run -d -p 80:80 -p 8000:8000 -e DOCKER=$(which docker) -v /var/run/docker.sock:/docker.sock alexagency/amhub
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Alex
  • 19
  • 1
  • Can you actually explain how one would accomplish what the original asker wants? They seem to be concerned that they have a lot of orphaned containers that it is tedious to fix. Adding another seems like a poor solution... – dovetalk Mar 12 '16 at 19:35
-2

I am suggesting you to stop the images first and then remove.

You could go like:

$ docker stop $(docker ps -a)
$ docker rm $(docker ps -a)
Siena
  • 612
  • 7
  • 21
-3

You can stop the docker container and once it is stopped you can remove the container.

Stop the container:

$ docker stop "containerID" - you can also mention the first two letters of the container ID, and it works.

Remove the container

$ docker rm "containerID" - again you can also mention the first two letters of the container

If these command do not let you stop/remove the containers, m,ake sure you have sudo access to docker host.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Kaul
  • 17
  • 1