🛠 Prerequisites

Ensure you have Docker installed on your system:

sudo apt update
  sudo apt install docker.io -y
  sudo systemctl enable --now docker
  • Verify installation:
docker --version

📌 Understanding Key Docker Commands

Before automating, familiarize yourself with these Docker commands:

  • List all running containers:
docker ps
  • List all containers (including stopped ones):
docker ps -a
  • Start a container:
docker start
  • Stop a container:
docker stop
  • Remove a container:
docker rm

📝 Writing the Automation Script

Create a new Bash script file:

vim manage_docker.sh

Paste the following script:

#!/bin/bash

echo "Docker Container Management Script"
echo "1. Start a container"
echo "2. Stop a container"
echo "3. Remove a container"
read -p "Choose an option (1-3): " option

case $option in
    1)
        read -p "Enter container name or ID to start: " container
        docker start "$container"
        echo "Container started."
        ;;
    2)
        read -p "Enter container name or ID to stop: " container
        docker stop "$container"
        echo "Container stopped."
        ;;
    3)
        read -p "Enter container name or ID to remove: " container
        docker rm "$container"
        echo "Container removed."
        ;;
    *)
        echo "Invalid option. Exiting."
        ;;
esac

Save and exit: CTRL + X, then Y, and hit Enter.


✅ Running the Script

  1. Give execution permission:
chmod +x manage_docker.sh
  1. Run the script:
./manage_docker.sh
  1. Follow the prompts to start, stop, or remove a container. 🎯