Docker image and container cleanup

Topic: Containers core

Summary

Remove unused images, containers, volumes, and networks with docker prune. Free disk space and avoid accumulation of dangling images and stopped containers. Use this when the Docker disk usage is high or when you want to keep the host clean.

Intent: How-to

Quick answer

  • Remove stopped containers: docker container prune. Remove unused images: docker image prune (dangling) or docker image prune -a (all unused). Remove unused volumes: docker volume prune (careful: deletes data). Remove unused networks: docker network prune.
  • All unused at once: docker system prune (containers, networks); docker system prune -a (plus all unused images); docker system prune -a --volumes (plus volumes; data loss). Check space: docker system df.
  • Remove specific: docker rm container; docker rmi image; docker volume rm volname. Do not prune volumes in production without confirming they are not in use; backup first if needed.

Prerequisites

Steps

  1. Check disk usage

    docker system df. Shows space used by images, containers, volumes, and build cache. Identify what is using space (e.g. many old images).

  2. Prune containers and images

    docker container prune removes stopped containers. docker image prune removes dangling images (no tag). docker image prune -a removes all images not used by a container (including tagged).

  3. Prune volumes and networks

    docker volume prune removes volumes not used by any container. Ensure no important data; backup first if unsure. docker network prune removes unused user networks.

  4. Full system prune (optional)

    docker system prune -a removes all unused containers, networks, and images. Add --volumes to include volumes (destructive). Use in CI or dev; in production prune selectively.

Summary

Use docker prune to remove unused containers, images, volumes, and networks. Use this to reclaim disk space and avoid clutter; be careful with volume prune in production.

Prerequisites

Steps

Step 1: Check disk usage

Run docker system df to see what is using space.

Step 2: Prune containers and images

Prune stopped containers and unused images; use -a for images only when you are sure.

Step 3: Prune volumes and networks

Prune volumes only after confirming no important data; prune unused networks.

Step 4: Full system prune (optional)

Use docker system prune -a when appropriate (e.g. CI); use —volumes only when volumes are disposable.

Verification

  • docker system df shows reduced usage; no required containers, images, or volumes were removed.

Troubleshooting

Accidentally removed volume — Restore from backup if you have one. Images still large — Use multi-stage builds and smaller bases; prune build cache with docker builder prune.

Next steps

Continue to