Skip to content

Instantly share code, notes, and snippets.

@Frederick888

Frederick888/control.sh

Last active Apr 21, 2020
Embed
What would you like to do?
Bash script to pull latest Docker container, (re)start container if needed, and clean up dangling images
#!/usr/bin/env bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" > /dev/null && pwd )"
IMAGE=
TAG='latest'
CONTAINER=
function printf() {
format="\e[1;31m$1\e[m"
shift
/usr/bin/printf "$format" $*
}
if [[ -z "$1" ]]; then
printf 'Please specify a service\n'
exit 1;
fi
SERVICE="$DIR/services/$1.sh"
if [[ ! -f "$SERVICE" ]]; then
printf 'Service file %s does not exist\n' "$SERVICE"
exit 1
fi
# shellcheck disable=1090
source "$SERVICE"
if [[ -z "$IMAGE" ]] || [[ -z "$CONTAINER" ]] || [[ "$(type -t docker_start_new)" != "function" ]]; then
printf 'Erroneous service file (IMAGE=%s, TAG=%s, CONTAINER=%s, docker_start_new=%s)\n' "$IMAGE" "$CONTAINER" "$TAG" "$(type -t docker_start_new)"
exit 1
fi
function docker_start() {
if [[ "$(type -t docker_prestart)" == "function" ]]; then
printf 'Running pre-start script\n'
docker_prestart
fi
printf 'Pulling latest image %s:%s\n' "$IMAGE" "$TAG"
docker pull "$IMAGE:$TAG"
CURRENT_IMAGE="$(docker container ls -a --filter="name=$CONTAINER" --format='{{.Image}}')"
if [[ -z "$CURRENT_IMAGE" ]]; then
printf '%s container not found\n' "$CONTAINER"
elif [[ "$CURRENT_IMAGE" != "$IMAGE:$TAG" ]]; then
printf 'Container %s is not running latest %s, gonna remove it\n' "$CONTAINER" "$IMAGE"
docker rm -f "$CONTAINER"
else
printf 'Container %s is already running the latest %s\n' "$CONTAINER" "$IMAGE"
printf 'Starting container %s\n' "$CONTAINER"
docker start "$CONTAINER"
exit 0
fi
printf 'Cleaning up dangling images\n'
DANGLING="$(docker image ls --filter=dangling=true -q "$IMAGE")"
if [[ -n "$DANGLING" ]]; then
docker rmi "$DANGLING"
else
printf 'No dangling images\n'
fi
docker_start_new
}
function docker_stop() {
printf 'Stopping container %s\n' "$CONTAINER"
docker stop "$CONTAINER"
if [[ "$(type -t docker_poststop)" == "function" ]]; then
printf 'Running post-stop script\n'
docker_poststop
fi
}
case "$2" in
start)
docker_start
;;
stop)
docker_stop
;;
restart)
docker_stop
docker_start
;;
remove|rm)
docker_stop
docker rm "$CONTAINER"
;;
*)
printf 'Unknown operation\n'
exit 1
;;
esac
#!/usr/bin/env bash
export IMAGE='gitlab/gitlab-runner'
export CONTAINER='gitlab-runner'
function docker_start_new() {
docker run -d --name "$CONTAINER" --restart unless-stopped \
-v /srv/gitlab-runner/config:/etc/gitlab-runner \
-v /var/run/docker.sock:/var/run/docker.sock \
--log-driver json-file --log-opt max-size=10m --log-opt max-file=3 \
"$IMAGE:$TAG"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment