Skip to content

Instantly share code, notes, and snippets.

@TimidRobot
Last active June 26, 2024 20:27
Show Gist options
  • Save TimidRobot/0386cd6610705a96b7837512517f23f9 to your computer and use it in GitHub Desktop.
Save TimidRobot/0386cd6610705a96b7837512517f23f9 to your computer and use it in GitHub Desktop.
macOS helper script to start services defined by docker compose and clean them up after they are stopped
#!/bin/bash
#
# Helper script to start services defined by docker compose and clean them up
# after they are stopped
# - launches docker if it is not currently running
# - requires macOS and Docker Desktop
#
set -o errexit
set -o errtrace
set -o nounset
# shellcheck disable=SC2154
trap '_es=${?};
printf "${0}: line ${LINENO}: \"${BASH_COMMAND}\"";
printf " exited with a status of ${_es}\n";
exit ${_es}' ERR
# https://en.wikipedia.org/wiki/ANSI_escape_code
E0="$(printf "\e[0m")" # reset
E30="$(printf "\033[30m")" # black foreground
E90="$(printf "\e[90m")" # bright black (gray) foreground
E107="$(printf "\033[107m")" # bright white background
#### FUNCTIONS ################################################################
print_header() {
# Print 80 character wide black on white heading
printf "${E30}${E107}# %-69s$(date '+%T') ${E0}\n" "${@}"
}
#### MAIN #####################################################################
print_header 'Ensure docker is running and display information'
if ! docker info &>/dev/null
then
echo -n "${E90}Waiting"
open -a Docker --fresh &
until docker info &>/dev/null
do
echo -n .
sleep 0.1
done
echo "${E0}"
fi
{
docker version \
| gsed \
-e'/API\|Go\|Git\|Built\|Arch\|Context\|Experimental\|^$/d' \
| gsed --null-data \
-e's/Server: /Server:\n /' \
-e's/Desktop /Desktop Version:/' \
-e's/:\n *Version/ Version/g'
docker compose version \
| gsed \
-e's/Docker //' \
-e's/version/Version:/'
} \
| gsed \
-e's/Version: */Version:|/' \
| column -s'|' -t
echo
# In some situations (ex. Docker restarted), the network may not be cleaned-up
# yet. Starting with `docker compose down` prevents `docker compose up` from
# failing with errors like:
# Error response from daemon: network [...] not found
print_header 'Stop and remove containers, networks'
docker compose down
echo
print_header 'Create and start containers'
docker compose up || true
echo
print_header 'Stop and remove containers, networks'
docker compose down
echo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment