Clean up unused docker resources to optimize disk space

To Nha Notes | July 31, 2024, 8:19 a.m.

1. Rebuild Without Cache

When building Docker images, consider using the --no-cache option to force a fresh build without relying on cached layers. This ensures that you start from scratch and avoid accumulating unnecessary data.

docker build --no-cache -t your-image-name .

2. Prune Unused Artifacts

Docker provides commands to clean up unused resources:

  • To remove stopped containers, unused volumes, and dangling images:

    docker system prune
    
docker image prune -f

docker volume prune -f
docker container prune --force
  • To specifically remove the build cache:

    docker builder prune
    
  • For docker-compose users:

    docker-compose down -v --rmi all --remove-orphans
    

3. Resize EC2 Root Volumes (For AWS EC2 Instances)

If you’re using AWS EC2 instances, consider resizing the root EBS volume from the AWS EBS console. This gives your instance more space to work with.

4. Check Docker Overlay2 Storage

Docker uses the Overlay2 storage driver. Verify the size of the Docker overlay storage directory (usually located at /var/lib/docker/overlay2). If it’s too large, clean it up.

5. Review Your Dockerfile and Images

Optimize your Dockerfile to minimize layers and reduce image size. Avoid unnecessary RUN commands. Regularly review and remove old or unused Docker images.