Docker Container Status script

To check the status of a Docker container, the following sample shell script can be used. The script also implements start, stop and restart actions upon the container.

#!/bin/bash
. /etc/rc.d/init.d/functions

CONTAINER=<YOUR_CONTAINER_NAME>

RUNNING=$(docker inspect --format="{ .State.Running }" $CONTAINER 2> /dev/null)

start(){
	if [ $? -eq 1 ]; then
	  echo "$CONTAINER does not exist."
	  exit 3
	fi

	echo "STARTING ..."
	docker start $CONTAINER
}

stop(){
	if [ $? -eq 1 ]; then
	  echo "$CONTAINER does not exist."
	  exit 3
	fi

	if [ "$RUNNING" == "false" ]; then
	  echo "$CONTAINER is not running."
	  exit 2
	fi

	echo "STOPPING ..."
	docker stop $CONTAINER
}

reload(){
	if [ $? -eq 1 ]; then
	  echo "UNKNOWN - $CONTAINER does not exist."
	  exit 3
	fi

	echo "RELOADING ..."
	docker restart $CONTAINER
}

status(){
	if [ $? -eq 1 ]; then
	  echo "$CONTAINER does not exist."
	  exit 3
	fi

	if [ "$RUNNING" == "false" ]; then
	  echo "$CONTAINER is not running."
	  exit 2
	fi

	STARTED=$(docker inspect --format="{ .State.StartedAt }" $CONTAINER)
	NAME=$(docker inspect --format="{ .Name }" $CONTAINER)
	NETWORKMODE=$(docker inspect --format="{ .HostConfig.NetworkMode }" $CONTAINER)
	NETWORK=$(docker inspect --format="{ .NetworkSettings.Networks."$NETWORKMODE".IPAddress }" $CONTAINER)

	echo "Ok - $CONTAINER is running. IP: $NETWORK, StartedAt: $STARTED, Named: $NAME"
}

case "$1" in
		start)
			start
			;;
		stop)
			stop
			;;
		restart)
			reload
			;;
		reload)
			reload
		;;
		status)
			status
			;;
		*)
		echo $"Usage: $0 {start|stop|restart|reload|status}"
esac