Managing Docker storage can sometimes be a challenging task, especially when dealing with the growth of the overlay or overlay2 directory in
/var/lib/docker. This article aims to provide a step-by-step approach to identify and clean up unused layers, helping you optimize disk space usage effectively.
Identifying Unused Containers and Images
1. Identify Unused Containers:
docker ps -a to list all containers. Remove unnecessary ones with
docker rm -vf <container_id>.
2. Identify Unused Images:
docker images -a to list all images. Remove unused images with
docker rmi -f <image_id>.
3. Prune Volumes:
Remove volumes not used by any container using
docker volume prune -f.
4. Clean Up Stopped Containers:
docker container prune -f to remove all stopped containers.
Understanding Overlay Layers
Overlay layers are crucial components of Docker storage. However, manually cleaning
/var/lib/docker/overlay2 is risky. Instead, focus on cleaning up containers and images as discussed above.
Restarting Docker Daemon
Sometimes, the Docker daemon may hold references to old layers. Restart it using
sudo service docker restart.
Leveraging Docker System Prune
docker system prune -af to remove stopped containers, dangling images, and unused networks and volumes.
Checking for Docker Cache
Docker caches layers for faster image builds. To rebuild an image without cache, use
docker build --no-cache -t <image_name> ..
Ensuring Docker Image References Are Cleared
Check if any containers are still using images you want to remove.