Skip to content

Instantly share code, notes, and snippets.

@DiegoSeC
Last active July 31, 2022 01:12
Show Gist options
  • Save DiegoSeC/42e12ac8054563a30583f95443465156 to your computer and use it in GitHub Desktop.
Save DiegoSeC/42e12ac8054563a30583f95443465156 to your computer and use it in GitHub Desktop.
Docker Compose Start Script Template
#!/bin/bash
# Stop docker containers if exists
names=$(docker ps --format "{{.Names}}")
if [ ! -z "$names" ]
then
printf "\n\e[1;31mKilling the following containers:\e[0m\n\n"
while read -r name
do
eval "docker container stop $name"
done <<< "$names"
fi
# If --build flag is present run docker-compose build
if [ "$1" == "--build" ]; then
printf "\n\e[1;34mBuilding Docker\e[0m\n\n"
docker-compose build
fi
# Run docker-compose in detach mode
printf "\n\e[1;36mDocker Compose Up\e[0m\n\n"
docker-compose up -d
# Running migrations, check if knexfile exists
names=$(docker ps --format "{{.Names}}")
printf "\n\e[1;33mRunning migration from containers\e[0m\n"
while read -r name
do
eval "docker exec $name /bin/sh -c \"[ -d \"/$name\" ] && cd /$name && test -f knexfile.js && npm run migration --if-present\""
done <<< "$names"
# Avoid repeating colors
declare -a colors
function _color {
COLOR="$(($RANDOM * 6 / 32767 + 1))"
if [[ ! " ${colors[@]} " =~ " ${COLOR} " ]]; then
colors+=($COLOR)
else
_color
fi
}
# Logging from containers
# CODE FROM: https://stackoverflow.com/a/38308974
printf "\n\e[1;35mLogging\e[0m\n\n"
esc=$(printf '\e')
while read -r name
do
# eval to show container name in jobs list
eval "_color"
eval "docker logs -f --tail=5 \"$name\" | sed -e \"s/^/${esc}[3${COLOR}m[-- $name --]${esc}[0m /\" &"
# For Ubuntu 16.04
#eval "docker logs -f --tail=5 \"$name\" |& sed -e \"s/^/[-- $name --] /\" &"
done <<< "$names"
function _exit {
printf "\n\n\e[1;31mStopping tails $(jobs -p | tr '\n' ' ')\e[0m\n"
# Using `sh -c` so that if some have exited, that error will
# not prevent further tails from being killed.
jobs -p | tr '\n' ' ' | xargs -I % sh -c "kill % || true"
printf "\n\e[1;32mDone\e[0m"
}
function _color {
COLOR = $($RANDOM * 6 / 32767 + 1)
echo $COLOR
}
# On ctrl+c, kill all tails started by this script.
trap _exit EXIT
# For Ubuntu 16.04
#trap _exit INT
# Don't exit this script until ctrl+c or all tails exit.
wait
@DiegoSeC
Copy link
Author

DiegoSeC commented Apr 9, 2019

Docker Compose Start Script Template

This is just a small template to create a docker script to build, run, migrate and logging all your dockers containers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment