Sub topic 3
One command for everything: `docker system prune`
Assume you know how to run containers, list images, and build images. The main risk in cleanup is deleting data that you still need. Start with inspection, then choose the narrowest command.
One command for everything
docker system prune removes stopped containers, unused networks, dangling images, and unused build cache. It does not remove volumes unless you explicitly add --volumes.
docker system prune
docker system prune -f --filter "until=168h"The first command asks for confirmation. The second removes matching objects older than seven days without prompting, so use it only in a controlled script or scheduled job.
| Command | Removes by default | Main risk |
|---|---|---|
| `docker system prune` | Stopped containers, unused networks, dangling images, build cache | Losing stopped containers you planned to restart |
| `docker system prune --volumes` | The default objects plus unused volumes | Deleting persistent application data |
Previewing a prune and avoiding data loss
Docker has no general dry-run flag for system prune. Use disk inspection and object lists as a manual preview:
docker system df
docker system df -v
docker ps -a --filter status=exited
docker image ls --filter dangling=true
docker volume ls --filter dangling=trueReview volume names carefully. A volume can contain a database even when no current container uses it. Run docker volume prune or docker system prune --volumes only after confirming that the data is disposable.
Container logs that grow without limit
Container logs can fill the disk even when images are clean. For Docker's json-file driver, configure rotation in /etc/docker/daemon.json:
{
"log-driver": "json-file",
"log-opts": {
"max-size": "10m",
"max-file": "3"
}
}Restart Docker after changing the daemon configuration. The setting applies to containers created afterward.
Keeping disk usage down in the first place
- Use
docker run --rmfor temporary containers. - Add build outputs, dependency directories, and secrets to
.dockerignore. - Use multi-stage builds so the final image contains only runtime files.
- Remove unused networks and caches periodically.
Scheduling cleanup safely
A weekly cron entry can remove stale objects while leaving volumes alone:
0 3 * * 0 docker system prune -f --filter "until=168h"Use an absolute Docker path on systems where cron has a limited PATH. Log the command's output and test it manually before scheduling it.
Exercise
Which option must you add before docker system prune can remove unused volumes?
Show answer
Add --volumes, after verifying that the volumes do not contain needed data.