Skip to content

Instantly share code, notes, and snippets.

@mehdihasan
Created July 16, 2024 13:01
Show Gist options
  • Save mehdihasan/5f645a2aefa3025b28aa037a41fde28a to your computer and use it in GitHub Desktop.
Save mehdihasan/5f645a2aefa3025b28aa037a41fde28a to your computer and use it in GitHub Desktop.
Automate docker container and image cleanup

Automate container and image cleanup

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.

Step 1: Create a Cleanup Script

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

Step 2: Test the Cleanup Script

./docker-cleanup.sh

Step 3: Set Up a Cron Job

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment