murkshelf

Docker: the cleanup commands I always forget

Every few weeks Docker eats 30 GB and I can’t remember the exact flags. Writing them down once and for all.

Look before you delete

docker system df          # how much Docker is actually using
docker ps -a              # containers, including stopped ones
docker images -a          # images, including intermediate layers
docker volume ls          # volumes

docker system df -v gives the per-item breakdown when you need to know exactly what is eating the space.

The safe sweep

docker system prune

Removes stopped containers, dangling images (untagged layers with no image pointing at them), unused networks, and dangling build cache. Running containers and their images are untouched. This is the one to run first.

The less safe sweep

docker system prune -a --volumes

Adds: all images not currently used by a running container, and anonymous volumes. Comfortable only when everything you care about can be rebuilt with docker compose up -d. On a CI machine — fine. On your laptop with that one database you never exported — check twice.

Targeted versions

docker container prune        # stopped containers only
docker image prune -a         # unused images only
docker volume prune           # unused volumes only
docker builder prune          # build cache only

Getting inside and out

docker exec -it db bash               # shell inside a running container
docker logs -f --tail 100 app         # follow the last 100 log lines
docker compose restart worker         # one service, config unchanged
docker compose up -d --force-recreate # pick up a changed image/env

The nuclear options

docker stop $(docker ps -q)           # stop everything running
docker rm $(docker ps -aq)            # remove every container
docker rmi $(docker images -q)        # remove every image

Not for production. Obviously. But on a dev box they turn ten minutes of clicking into ten seconds.