Docker clean up overlay

Updated: July 28, 2020

If you are having docker /var/lib/docker/overlay use almost of your storage, then you should ran some clean up code below.

From what I having on my 10Gb only VPS

# df -H
Filesystem              Size  Used Avail Use% Mounted on
udev                    238M     0  238M   0% /dev
tmpfs                    51M  5.7M   46M  12% /run
/dev/mapper/vg_jh-root  5.8G  5.5G  5.2M 100% /
tmpfs                   254M     0  254M   0% /dev/shm
tmpfs                   5.3M     0  5.3M   0% /run/lock
tmpfs                   254M     0  254M   0% /sys/fs/cgroup
/dev/vda1               487M  125M  333M  28% /boot
overlay                 5.8G  5.5G  5.2M 100% /var/lib/docker/overlay2/59983d9e0769f2ec06cf348b0a536c779cb3ad94c038ba3322239255e5965f37/merged
tmpfs                    51M     0   51M   0% /run/user/0

Code to run

docker volume rm $(docker volume ls -qf dangling=true)
docker system prune -a -f

What it does is try to remove other docker images and container, exclude current running container.

Docker clean unused images

// list all docker images 
docker images

// remove all images
docker rmi $(docker images -a -q)
// List unused docker images with Pattern
docker images -a |  grep "pattern"

// remove unused docker image via KEYWORD || Pattern

docker images -a | grep "ecr" | awk '{print $3}' | xargs docker rmi --force

Clean by status

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

remove any stopped containers and all unused images (not just dangling images), add the -a flag to the command

docker system prune -a

Remove dangling image

// List
docker images -f dangling=true

// Remove
docker images purge

Reference: https://www.digitalocean.com/community/tutorials/how-to-remove-docker-images-containers-and-volumes

Photo by Sarah Dorweiler on Unsplash