To remove old Docker containers, you can use Docker commands to target stopped, exited, or unused containers. Below are multiple methods with examples for different scenarios:
1. Remove All Stopped Containers
Delete containers that have exited or stopped:
docker container prune
# Or
docker rm $(docker ps -aq --filter "status=exited")
Output:
Deleted Containers: 3a1b2c3d4e...
Total reclaimed space: 120MB
2. Remove Containers Older Than a Specific Time
Delete containers created more than 24 hours ago:
docker ps -a --format "{{.ID}} {{.CreatedAt}}" | \
awk '$2 <= "'$(date -d '24 hours ago' +'%Y-%m-%dT%H:%M:%S')'" {print $1}' | \
xargs docker rm
Explanation:
docker ps -a
lists all containers.--format
customizes the output to show container ID and creation time.awk
filters containers older than 24 hours.xargs docker rm
removes the identified containers.
3. Remove Containers by Status
Delete exited or created containers:
# Remove all exited containers:
docker rm $(docker ps -aq --filter "status=exited")
# Remove all created containers (never started):
docker rm $(docker ps -aq --filter "status=created")
4. Force-Remove All Containers (Including Running Ones)
Caution: This stops and removes all containers:
docker rm -f $(docker ps -aq)
5. Remove Containers by Label or Name
Delete containers with a specific label or name pattern:
# By label:
docker rm $(docker ps -aq --filter "label=experimental")
# By name (e.g., "old-*"):
docker rm $(docker ps -aq --filter "name=old-*")
6. Clean Up with docker system prune
Remove all stopped containers, unused networks, dangling images, and build cache:
docker system prune
Add -a
to remove all unused images (not just dangling ones):
docker system prune -a
7. Automate Cleanup with a Script
Save this script as docker-cleanup.sh
and run it periodically:
#!/bin/bash
# Remove containers older than 7 days
docker ps -a --format "{{.ID}} {{.CreatedAt}}" | \
awk '$2 <= "'$(date -d '7 days ago' +'%Y-%m-%dT%H:%M:%S')'" {print $1}' | \
xargs docker rm -f
# Remove unused volumes
docker volume prune -f
# Remove dangling images
docker image prune -f
Summary Table
Command | Use Case |
---|---|
docker container prune | Quick removal of all stopped containers. |
docker rm $(docker ps -aq --filter "...") | Targeted removal by status/label. |
docker system prune | Full system cleanup (containers, networks, images). |
docker rm -f $(docker ps -aq) | Force-remove all containers (use with caution!). |
Key Notes
- Safety: Always verify containers with
docker ps -a
before deletion. - Filters: Use
--filter
withstatus
,label
, orname
for precision. - Automation: Schedule cleanup scripts with
cron
(Linux) or Task Scheduler (Windows).
By combining these methods, you can efficiently manage Docker container lifecycle!