Debug School

rakesh kumar
rakesh kumar

Posted on

Shell scripts for managing Docker containers using loops and conditionals

Script for Managing Containers:
Stop All Running Containers:

#!/bin/bash
for container_id in $(docker ps -q); do
    docker stop $container_id
done
Enter fullscreen mode Exit fullscreen mode

Remove All Stopped Containers:

for container_id in $(docker ps -aq); do
    docker rm $container_id
done
Enter fullscreen mode Exit fullscreen mode

Restart Containers Based on a Condition:

#!/bin/bash
for container_id in $(docker ps -aq); do
    restart_needed=false
    # Add condition to check if restart is needed
    if [ $restart_needed == true ]; then
        docker restart $container_id
    fi
done
Enter fullscreen mode Exit fullscreen mode

Script for Managing Images:
Remove All Unused Images:

#!/bin/bash
docker image prune -f
Enter fullscreen mode Exit fullscreen mode

Remove All Images Except a Specific One:

#!/bin/bash
image_to_keep="your_image_name"
for image_id in $(docker images -q); do
    if [ $image_id != $(docker images -q $image_to_keep) ]; then
        docker rmi $image_id
    fi
done
Enter fullscreen mode Exit fullscreen mode

Docker Compose Script:
Run Docker Compose for Multiple Compose Files:

#!/bin/bash
docker-compose -f docker-compose-file1.yml -f docker-compose-file2.yml up -d
Enter fullscreen mode Exit fullscreen mode

Conditional Commands Inside Containers:
Execute a Command Inside Running Containers Based on a Condition:

#!/bin/bash
for container_id in $(docker ps -aq); do
    condition_met=false
    if [ $condition_met == true ]; then
        docker exec $container_id your_command
    fi
done
Enter fullscreen mode Exit fullscreen mode

Cleaning Up Script:
Clean Up Docker Resources Based on Conditions:

#!/bin/bash
prune_condition=true

if [ $prune_condition == true ]; then
    docker container prune -f
    docker image prune -f
    docker volume prune -f
    docker network prune -f
fi
Enter fullscreen mode Exit fullscreen mode

Dynamic Commands Based on Container List:
Run Command on Containers Matching a Pattern:

#!/bin/bash
pattern="your_pattern"
command_to_run="your_command"

for container_id in $(docker ps --filter "name=$pattern" -q); do
    docker exec $container_id $command_to_run
done
Enter fullscreen mode Exit fullscreen mode

These scripts use for loops and conditionals to iterate through containers, images, or other Docker-related entities and perform actions based on specified conditions. Adapt these scripts according to your specific use case and requirements.

Top comments (0)