I am running the following script to check if my docker services are running. If a service isn’t running, the script sent a message to my rocketchat app via webhook like this:
#!/bin/sh # Shell script to monitor docker services every minute # ------------------------------------------------------------------------------------------- # set webhook url RocketURL=https://example.com/webhook; # get all containers Containers=$(docker ps -a | awk '{if(NR>1) print $NF}') for i in $Containers do isServiceRunning=$(docker inspect --format="{{.State.Running}}" $i) if [ $isServiceRunning = false ]; then /home/user/scripts/sendMessage.sh -b "The Docker Service: $i is not running. Please fix it" -u $RocketURL fi done
It works, but if a docker service is not running, i receive the message every minute again, because the script is running every minute via cronjob. So how can i prevent this? I only want to get one message, when the service is not running. How can i do that?
Advertisement
Answer
Create a file when sending the message, and only send the message when the file doesn’t exist. Delete the file if the service is running.
for container in $Containers ; do processed=/tmp/noturn."$container" isServiceRunning=$(docker inspect --format="{{.State.Running}}" "$container") if [ "$isServiceRunning" = false ] ; then if [ ! -e "$processed" ] ; then /home/user/scripts/sendMessage.sh -b "The Docker Service: $i is not running. Please fix it" -u "$RocketURL" fi touch "$processed" else rm -f "$processed" fi done