Skip to content

Instantly share code, notes, and snippets.

@awadhwana
Last active May 15, 2022 08:29
Show Gist options
  • Save awadhwana/ea76735cad07196b14b6ef9b93ac5e71 to your computer and use it in GitHub Desktop.
Save awadhwana/ea76735cad07196b14b6ef9b93ac5e71 to your computer and use it in GitHub Desktop.
A script to start the docker containers from the compose yml.
#!/bin/sh
set -e
## usage
# docker-init up -> start the containers
# docker-init -> stops the containers
# https://24ankitw.medium.com/managing-docker-containers-3d0bcc54405
command_exists() {
command -v "$@" >/dev/null 2>&1
}
fmt_error() {
printf '%sError: %s%s\n' "$BOLD$RED" "$*" "$RESET" >&2
}
setup_color() {
RED=$(printf '\033[31m')
GREEN=$(printf '\033[32m')
YELLOW=$(printf '\033[33m')
BLUE=$(printf '\033[34m')
BOLD=$(printf '\033[1m')
RESET=$(printf '\033[m')
}
setup_color
command_exists docker || {
fmt_error "docker is not installed"
exit 1
}
command_exists docker-compose || {
fmt_error "docker-compose is not installed"
exit 1
}
printf %s "$BLUE"
cat <<'EOF'
____ _
| _ \ ___ ___| | _____ _ __
| | | |/ _ \ / __| |/ / _ \ '__|
| |_| | (_) | (__| < __/ |
|____/ \___/ \___|_|\_\___|_|
____ _ _
/ ___|___ _ __ | |_ __ _(_)_ __ ___ _ __ ___
| | / _ \| '_ \| __/ _` | | '_ \ / _ \ '__/ __|
| |__| (_) | | | | || (_| | | | | | __/ | \__ \
\____\___/|_| |_|\__\__,_|_|_| |_|\___|_| |___/
... lodaing 🐳
EOF
printf %s "$RESET"
echo "${YELLOW}Script Execution started!!!${RESET}"
running_containers=($(docker ps --format '{{.Names}}'))
## Directory contining the sub dirs which has the docker-compose.yml file
docker_compose_dir=$HOME/devops/docker
if [[ "$1" = "up" ]]; then
for d in $docker_compose_dir/*/
do
current_dirname=$(basename ${d})
# avoids prompt to start the running container
if [[ " ${running_containers[@]} " =~ " ${current_dirname} " ]]; then
continue
fi
cd "$d"
echo "\n${GREEN} ${BOLD}$d ${RESET}"
read -p " Do you want to start this container ${YELLOW}y/n${RESET} : " input
if [ "$input" = "y" ]; then
echo "${GREEN} ${BOLD}Stating the container ${RESET}"
command docker-compose up -d
fi
done
else
for d in $docker_compose_dir/*/
do
current_dirname=$(basename ${d})
# avoids prompt to stop the non-running container
if [[ " ${running_containers[@]} " =~ " ${current_dirname} " ]]; then
cd "$d"
echo "\n${GREEN} ${BOLD}$d ${RESET}"
read -p " Do you want to shut-down this container ${YELLOW}y/n${RESET} : " input
if [ "$input" = "y" ]; then
echo "${GREEN} ${BOLD}Stating the container ${RESET}"
command docker-compose down
fi
fi
done
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment