Docker

Determining and Clearing Container Disk Usage in Overlay2

Show disk usage using docker df:

docker system df

Should output similar to below:

TYPE                TOTAL               ACTIVE              SIZE                RECLAIMABLE
Images              23                  22                  11.15GB             799.2MB (7%)

Containers          28                  27                  2.751GB             0B (0%)

Local Volumes       19                  19                  477.2MB             0B (0%)

Build Cache         0                   0                   0B                  0B

Show disk usage using du:

du -shc /var/lib/docker/overlay2/*/diff | grep total

should output similar to below:

15G     total

Show disk usage using du:

du -h /var/lib/docker | sort -h

Script to clear overlay2 storage and volumes :

#!/bin/bash

# remove exited containers:
docker ps --filter status=dead --filter status=exited -aq | xargs -r docker rm -v
    
# remove unused images:
docker images --no-trunc | grep '<none>' | awk '{ print $3 }' | xargs -r docker rmi

# remove unused volumes:
find '/var/lib/docker/volumes/' -mindepth 1 -maxdepth 1 -type d | grep -vFf <(
  docker ps -aq | xargs docker inspect | jq -r '.[] | .Mounts | .[] | .Name | select(.)'
) | xargs -r rm -fr

Docker Logs can also take up a significant amount of space. Logs are located under /var/lib/docker/containers/<container-id>/<container-id-json.log.

Logs can be set to maximum size and number by setting the following in docker-compose.yml:

services:
  my-app:
    image: my-app:latest
    container_name: mycontainer
    logging:
      options:
        max-size: 10m
....

Additionally, you can setup logging driver default options at the daemon level as described in the URL below:

https://docs.docker.com/config/containers/logging/configure/#configure-the-default-logging-driver