DEV Community

Kishore Suzil
Kishore Suzil

Posted on

Automate Docker Container Management with a Simple Bash Script

🛠 Prerequisites

Ensure you have Docker installed on your system:

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

📌 Understanding Key Docker Commands

Before automating, familiarize yourself with these Docker commands:

  • List all running containers:
  docker ps
Enter fullscreen mode Exit fullscreen mode
  • List all containers (including stopped ones):
  docker ps -a
Enter fullscreen mode Exit fullscreen mode
  • Start a container:
  docker start <container_name_or_id>
Enter fullscreen mode Exit fullscreen mode
  • Stop a container:
  docker stop <container_name_or_id>
Enter fullscreen mode Exit fullscreen mode
  • Remove a container:
  docker rm <container_name_or_id>
Enter fullscreen mode Exit fullscreen mode

📝 Writing the Automation Script

Create a new Bash script file:

vim manage_docker.sh
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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


✅ Running the Script

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

Top comments (0)

👋 Kindness is contagious

Please show some love ❤️ or drop a kind note in the comments if this was helpful to you!

Got it!