How to Clean Up Orphaned Docker Volumes After Container Removal


2 views

We've all been there - you've removed Docker containers with docker rm but forgot the -v flag, or perhaps you used container pruning commands that didn't handle volumes properly. These "orphaned" volumes continue occupying disk space while being untethered from any container.

First, let's find these lingering volumes:

# List all volumes (including orphaned ones)
docker volume ls

# Filter for dangling volumes specifically
docker volume ls -f dangling=true

For targeted removal of specific volumes:

# Remove a single volume by name
docker volume rm volume_name

# Remove all unused volumes (careful!)
docker volume prune

Create a scheduled cleanup script (save as docker-cleanup.sh):

#!/bin/bash
# Remove stopped containers
docker container prune -f

# Remove dangling images
docker image prune -f

# Remove unused networks
docker network prune -f

# Remove orphaned volumes
docker volume prune -f
  • Always use docker rm -v when removing containers
  • Specify --rm flag for temporary containers: docker run --rm -v myvol:/data
  • Consider named volumes for important data: docker volume create important_data

Before deleting, examine volume contents:

# Create temporary container to inspect volume
docker run -it --rm \
    -v volume_name:/volume_data \
    alpine ls -la /volume_data

Many Docker users face this scenario: you've deleted containers using docker rm without the -v flag, and now you're left with unused volumes taking up disk space. These "orphaned volumes" can accumulate over time, especially in development environments where containers are frequently created and destroyed.

First, let's find these unused volumes:

docker volume ls -f dangling=true

This command lists all volumes not referenced by any containers. You'll see output like:

DRIVER    VOLUME NAME
local     3a7b5e2c1d9f...
local     f8d4e6c3a2b1...

To remove all dangling volumes at once:

docker volume prune

This will prompt for confirmation before deleting. For automated scripts, use:

docker volume prune -f

If you need to remove specific volumes:

docker volume rm VOLUME_NAME

For example:

docker volume rm 3a7b5e2c1d9f

Always use the -v flag when removing containers:

docker rm -v container_name

Or when using docker-compose down, add:

docker-compose down -v

To see how much space volumes are consuming:

docker system df -v

This helps identify large volumes that might be worth cleaning up.

For regular maintenance, consider adding this to your crontab:

0 3 * * * /usr/bin/docker volume prune -f

This runs a nightly cleanup at 3 AM.