Removing unused Docker containers and images - tooltwist/documentation GitHub Wiki

Containers

In Docker, containers are not removed when they stop, but remain so that the log files may be viewed. Over time these old containers build up.

In Amazon ECS, a service will repeatedly try to the task if there is an error, and each attempt may leave multiple containers stopped, but still occupying space within Docker. After a day or two Docker may run out of resources and will not be able to start containers, even if there are no errors.

The solution is to periodically strip out any unused containers.

To see stopped containers, run

$ docker ps -a

To remove unused containers:

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

Beware that just because a container is stopped does not mean that it is not needed. Use common sense with this command.

Images

In a similar manner, images that are not being used continue to use resources. If an EC2 instance within the cluster has been used to run many different applications, it will still contain the images for all those applications.

The following command will remove any images that are not currently being used by any containers:

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

Beware that images will also be removed for any applications that are currently not running.