BASH
Manage Multiple Docker Containers with a Single Command
Create a unified script to start, stop, or restart multiple Docker containers by name or using a common naming convention, simplifying Docker management.
#!/bin/bash
# --- Configuration ---
# List of container names to manage. Can be full names or partial matches.
CONTAINER_NAMES=("my-webapp-container" "my-db-container" "my-cache-container")
# Or if you have a common prefix, you can find them dynamically:
# CONTAINER_PREFIX="my-app-"
# CONTAINER_NAMES=($(docker ps -a --format "{{.Names}}" | grep "^${CONTAINER_PREFIX}"))
# --- Script Logic ---
ACTION="$1"
if [ -z "$ACTION" ]; then
echo "Usage: $0 {start|stop|restart|status}" >&2
exit 1
fi
if [ ${#CONTAINER_NAMES[@]} -eq 0 ]; then
echo "No containers configured to manage. Exiting." >&2
exit 1
fi
echo "Performing $ACTION on the following Docker containers:"
for name in "${CONTAINER_NAMES[@]}"; do
echo "- $name"
done
for CONTAINER in "${CONTAINER_NAMES[@]}"; do
case "$ACTION" in
start)
echo "Starting $CONTAINER..."
docker start "$CONTAINER"
;;
stop)
echo "Stopping $CONTAINER..."
docker stop "$CONTAINER"
;;
restart)
echo "Restarting $CONTAINER..."
docker restart "$CONTAINER"
;;
status)
echo "Status of $CONTAINER:"
docker inspect --format='{{.State.Status}}' "$CONTAINER" 2>/dev/null || echo "Not found"
;;
*)
echo "Invalid action: $ACTION" >&2
echo "Usage: $0 {start|stop|restart|status}" >&2
exit 1
;;
esac
done
echo "All requested actions completed."
How it works: This script simplifies the management of multiple Docker containers. You can define a list of container names, or even dynamically discover them based on a common prefix. By passing 'start', 'stop', 'restart', or 'status' as an argument to the script, it will iterate through the configured containers and apply the specified Docker command to each, significantly reducing repetitive typing and making it easier to manage development or staging environments.