Wow! You made it this far! This is incredible!
The next challenge I have is attempting to find out which containers are associated to which image. Natively, there isn’t any good/easy way to be able to do this but I have a solution! My next bash script will create some output that shows which containers belong to which docker image.
Github repository with the scripts are available here –> https://github.com/TheScriptGuy/docker-operations
image_containers.sh
What’s nice about this script is that it will auto-size the columns based on the maximum length of the repository/image_name:image_version when displaying the output.
#!/bin/bash
# Check if Docker is installed
if ! command -v docker &> /dev/null; then
echo "Docker command not found. Please install Docker and try again."
exit 1
fi
# Separator for better readability
echo "--------------------------------"
echo "Associations: Image (Image ID) -> Containers"
echo "--------------------------------"
# Fetch unique image IDs from all containers (running and stopped)
used_image_ids=$(docker ps -a --format "{{.Image}}" | sort | uniq)
# Initialize a variable to store the max length of the image_info string
max_length=0
# Determine the maximum length of image_info string for better formatting
for image_id in $used_image_ids; do
image_info=$(docker images --filter=reference="$image_id" --format "{{.Repository}}:{{.Tag}} ({{.ID}})")
if (( ${#image_info} > max_length )); then
max_length=${#image_info}
fi
done
# Iterate through each unique image ID
for image_id in $used_image_ids; do
# Get the repository, tag, and ID of the image
image_info=$(docker images --filter=reference="$image_id" --format "{{.Repository}}:{{.Tag}} ({{.ID}})")
# If image_info is available
if [[ ! -z "$image_info" ]]; then
# Get all container names (running/stopped) associated with the image
container_names=$(docker ps -a --filter ancestor="$image_id" --format "{{.Names}}" | tr '\n' ', ' | sed 's/,$//')
# If no containers, set a placeholder text
[[ -z "$container_names" ]] && container_names="No containers associated."
# Add padding spaces to image_info for alignment
printf -v padded_image_info "%-${max_length}s" "$image_info"
# Display the information with formatted output
echo "$padded_image_info --> $container_names"
fi
done
Here is some example output:
$ ./image-container.sh
--------------------------------
Associations: Image (Image ID) -> Containers
--------------------------------
server/work-node:1.5 (43b4d60360ff) --> work-node5,work-node6
server/mycertimage:0.26 (c4b7bdabfa1e) --> container1,container2,container3
server/mycontainertest:1.0 (6b61ce516960) --> mycontainertest
server/syslog-ng:2.1 (b38bfac413fd) --> syslog-ng2
Take note that it’s displaying the containers associated with the image and the associated image id.
