Skip to content

Instantly share code, notes, and snippets.

@richxcame
Created January 17, 2022 19:02
Show Gist options
  • Save richxcame/3259f5147429bd4570053da62ec785cb to your computer and use it in GitHub Desktop.
Save richxcame/3259f5147429bd4570053da62ec785cb to your computer and use it in GitHub Desktop.

Bash script for docker

Give permission to booking.sh

sudo chmod +x scriptname.sh

booking.sh

#!/bin/bash

CLEAN="clean"
RUN="run"
STOP="stop"

if [ "$#" -eq 0 ] || [ $1 = "-h" ] || [ $1 = "--help" ]; then
    echo "Usage: ./booking [OPTIONS] COMMAND [arg...]"
    echo "       ./booking [ -h | --help ]"
    echo ""
    echo "Options:"
    echo "  -h, --help    Prints usage."
    echo ""
    echo "Commands:"
    echo "  $CLEAN      - Stop and Remove imoney containers."
    echo "  $RUN        - Build and Run imoney."
    echo "  $STOP       - Stop imoney."
    exit
fi

clean() {
  stop_existing
  remove_stopped_containers
  remove_unused_volumes
}

run() {
  echo "Cleaning..."
  clean
  
  echo "Running docker..."
  docker-compose up --build
}

stop_existing() {
  BOOKING="$(docker ps --all --quiet --filter=name=hotel-reservation)"
  REDIS="$(docker ps --all --quiet --filter=name=hotel-reservation-redis)"
  MONGO="$(docker ps --all --quiet --filter=name=hotel-reservation-mongo)"

  if [ -n "$BOOKING" ]; then
    docker stop $BOOKING
  fi

  if [ -n "$REDIS" ]; then
    docker stop $REDIS
  fi

  if [ -n "$MONGO" ]; then
    docker stop $MONGO
  fi
}

remove_stopped_containers() {
  CONTAINERS="$(docker ps -a -f status=exited -q)"
	if [ ${#CONTAINERS} -gt 0 ]; then
		echo "Removing all stopped containers."
		docker rm $CONTAINERS
	else
		echo "There are no stopped containers to be removed."
	fi
}

remove_unused_volumes() {
  CONTAINERS="$(docker volume ls -qf dangling=true)"
	if [ ${#CONTAINERS} -gt 0 ]; then
		echo "Removing all unused volumes."
		docker volume rm $CONTAINERS
	else
		echo "There are no unused volumes to be removed."
	fi
}

if [ $1 = $CLEAN ]; then
  echo "Cleaning..."
	clean
	exit
fi

if [ $1 = $RUN ]; then
	run
	exit
fi

if [ $1 = $STOP ]; then
	stop_existing
	exit
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment