Applies to: Docker Engine 29.8.1 (all commands and messages tested)
Old containers, unused images and forgotten volumes can fill a server’s disk. These commands show what exists and remove what you no longer need. Start with the list commands, and take care with anything that removes volumes: that is where your data lives.
See what is there
docker ps # running containers docker ps -a # all containers, also stopped ones docker ps -aq # only the IDs (useful in scripts) docker images # images docker volume ls # volumes docker system df # disk space used by each type
docker system df printed this in our test:
TYPE TOTAL ACTIVE SIZE RECLAIMABLE Images 3 0 120.2MB 120.1MB (99%) Containers 0 0 0B 0B Local Volumes 1 0 0B 0B Build Cache 0 0 0B 0B
Remove containers
docker stop web && docker rm web docker rm -f web # stop and remove in one step docker container prune # all stopped containers docker rm $(docker ps -aq -f status=exited) # the same, another way
Removing a running container without -f fails with: cannot remove container "web": container is running: stop the container before removing or force remove.
Remove images
docker rmi nginx:alpine docker image prune # only "dangling" images (untagged leftovers of builds) docker image prune -a # every image not used by a container
An image used by a container can’t be removed: conflict: unable to delete nginx:alpine (must be forced) - container 00e0721c404c is using its referenced image. Remove the container first. In our test, docker image prune -a freed 120.2 MB. Removed images are simply downloaded again the next time you need them.
Remove volumes (careful)
docker volume rm my-volume docker volume prune # unused ANONYMOUS volumes only docker volume prune -a # also unused NAMED volumes
Our test confirmed that plain docker volume prune kept the named volume; -a would have removed it. Named volumes usually hold databases and uploads, so back them up first.
Clean everything unused at once
docker system prune # stopped containers, unused networks, dangling images, build cache docker system prune -a # also all unused images docker system prune --volumes # also anonymous volumes
Docker asks for confirmation; add -f in scripts. To keep recent images, filter by age: docker image prune -a --filter "until=168h" (older than 7 days).
Docker Compose projects
docker compose down # removes the project's containers and network, keeps volumes docker compose down -v # ALSO deletes the project's volumes and their data
Installing Docker: install Docker on Debian and Ubuntu. Compose files: Docker Compose basics.
Ucartz services for this topic
- KVM VPS hosting: NVMe SSD and full root access, with Free Basic Managed Support.
- Linux server management: hardening, patching, monitoring and automation for Ubuntu, Debian, RHEL and AlmaLinux.
- Hire an expert: engineers per 15 minutes, per hour or per month, with no contract.
