Automating Cleanup of Idle Docker Jenkins Nodes

Managing Docker containers within a Jenkins environment is essential for efficient resource utilization. One key aspect involves cleaning up idle containers, removing unused images, and clearing dangling volumes. To streamline this process, a bash script can be used to automate these tasks. Below is an example script designed for this purpose:

#!/bin/bash

# Stop and remove idle containers
docker ps --filter "name=<container_prefix>_*" --format "{{.ID}}" | while read -r container_id
do
    echo "Stopping container: $container_id"
    docker stop "$container_id"

    echo "Removing container: $container_id"
    docker rm "$container_id"
done

# Remove unused Docker images
docker images --format "{{.ID}} {{.Repository}}" | while read -r image_id repository
do
    # Exclude necessary images (e.g., base Jenkins image)
    if [[ "$repository" != "<necessary_image>" ]]; then
        echo "Removing image: $repository"
        docker rmi "$image_id"
    fi
done

# Clean up Docker volumes
docker volume ls -qf dangling=true | while read -r volume_name
do
    echo "Removing volume: $volume_name"
    docker volume rm "$volume_name"
done

Please Note: Before usage, ensure to customize the script according to your Docker and Jenkins setup:

  1. Replace <container_prefix> with the specific prefix used for your Jenkins containers.
  2. Update <necessary_image> with the repository name of any essential images that should be excluded from removal (such as the base Jenkins image).

To utilize this script, follow these steps:

  1. Save the script into a file, for instance, cleanup.sh.
  2. Make the script executable using chmod +x cleanup.sh.
  3. Execute the script in the terminal by running ./cleanup.sh.

Important Disclaimer: This script serves as a basic example and might need adjustments to suit your unique Docker configuration and Jenkins environment. Before running it, thoroughly review and tailor the script to match your specific requirements.

By automating the cleanup of idle Docker Jenkins nodes, you can ensure a more organized and efficient infrastructure, optimizing resources and enhancing system performance.