To automatically delete Docker containers and images older than 15 days, we can set up a cron job that runs a script at specified intervals.
Create a file named docker-cleanup.sh
with the following content:
#!/bin/bash
# Define cutoff date in Unix timestamp (15 days ago)
cutoff=$(date -d '15 days ago' +%s)
# Remove containers that are exited for more than 15 days
docker ps -a -q -f "status=exited" --format "{{.ID}} {{.CreatedAt}}" | while read -r container_id created_at; do
created_timestamp=$(date -d "$created_at" +%s)
if [ $created_timestamp -lt $cutoff ]; then
echo "Removing container $container_id (created at $created_at)"
docker rm $container_id
fi
done
# Remove images older than 15 days
docker images --format "{{.Repository}}:{{.Tag}} {{.ID}} {{.CreatedAt}}" | while read -r line; do
image_info=($line)
image_name=${image_info[0]}
image_id=${image_info[1]}
image_created_at=${image_info[2]}
image_timestamp=$(date -d "$image_created_at" +%s)
# Skip if image ID is <none> (invalid reference format)
if [ "$image_id" == "<none>" ]; then
continue
fi
if [ $image_timestamp -lt $cutoff ]; then
echo "Removing unused image $image_name (ID: $image_id, created at $image_created_at)"
docker rmi $image_id
else
echo "Skipping image $image_name (ID: $image_id) removal because it is not older than 15 days or still in use"
fi
done
Save this script to a convenient location, for example, /opt/docker-cleanup/docker-cleanup.sh. Make sure the script is executable:
chmod +x /opt/docker-cleanup/docker-cleanup.sh
./docker-cleanup.sh
Now, automate the cleanup process using a cron job. Open the crontab editor:
crontab -e
Add the following line to run the cleanup script every day at a specific time (for example, 9:00 AM):
0 9 * * * /opt/docker-cleanup/docker-cleanup.sh >> /var/log/docker-cleanup.log 2>&1
The output of the script will be logged to /var/log/docker-cleanup.log
for monitoring and troubleshooting purposes.