BASH
Control Multiple Docker Containers with a Single Bash Command
Simplify Docker container management with a Bash script. Easily start, stop, or restart a group of specified Docker containers, streamlining your development or deployment workflow.
#!/bin/bash
# Configuration: List of container names to manage
CONTAINER_NAMES=("my-webapp-container" "my-db-container" "my-redis-container")
# --- Usage --- #
if [ -z "$1" ]; then
echo "Usage: $0 [start|stop|restart|status]"
exit 1
fi
COMMAND=$1
# --- Function to execute Docker command --- #
execute_docker_command() {
local cmd="$1"
local name="$2"
echo "Executing 'docker ${cmd} ${name}'..."
docker "${cmd}" "${name}"
if [ $? -ne 0 ]; then
echo "Warning: Command '${cmd}' failed for container '${name}'."
fi
}
# --- Main Logic --- #
case "${COMMAND}" in
start|stop|restart)
for CONTAINER in "${CONTAINER_NAMES[@]}"; do
execute_docker_command "${COMMAND}" "${CONTAINER}"
done
echo "All specified containers processed with command: ${COMMAND}"
;;
status)
echo "--- Status of specified containers ---"
for CONTAINER in "${CONTAINER_NAMES[@]}"; do
echo "Container: ${CONTAINER}"
docker ps --filter "name=${CONTAINER}" --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
if [ $? -ne 0 ]; then
echo "Error checking status for container '${CONTAINER}'."
fi
done
;;
*)
echo "Invalid command: ${COMMAND}"
echo "Usage: $0 [start|stop|restart|status]"
exit 1
;;
esac
How it works: This Bash script allows a web developer to control multiple Docker containers with a single command. You define a list of `CONTAINER_NAMES` you wish to manage. The script takes an argument (`start`, `stop`, `restart`, or `status`) and iterates through the defined container names, applying the chosen Docker command to each. This centralizes the management of interconnected services (e.g., a web app, database, and cache) into one simple script, making development and deployment workflows more efficient. The 'status' command provides a quick overview of their current state.