HOW TO WRITE DOCKER CONTAINER STOP ALERT ON EMAIL FROM BASH SCRIPT: DOCKER MONITORING

From this tutorial you can write bash script to get email when your container will be in any other state except running like stop, exited and others.

linuxawspoint_docker_scripts

Assume that we have running containers are

  • Test1
  • Test2
  • Test3
  • Test4
  • Mail server details to send an email and mail template as per your content

Copy the below code in your script file and make changes as per your environment.

vim docker_con.sh

#!/bin/bash

#to get the IP of server where containers are running
ip=curl icanhazip.com
#define the variable
list_of_containers="Test1 Test2 Test3 Test4"
containers=docker ps -f status=running --format "{{.Names}}"
for container in $list_of_containers
do
	if echo $containers | grep -q $container 
	 then echo "$container online"
	else
		curl --location --request POST 'https://mail.linuxawspoint.com/v1/alert/mails' \
          --header 'Authorization: App API-kEY' \
          --header 'Content-Type: application/json' \
          --data-raw '{
    "template": "DOCKER_ALERT",
    "channel": "EMAIL",
    "source": "Alerts",
    "tasks": [
        {
            "to_address": "devopsalert@linuxawspoint.com",
            "params": {
                "Container": "'${container}'",
                "IP": "'${ip}'"
            }
        }
    ]
}'
		
	fi
done
exit 0

You can configure cron job to run the above script on your server.
Suppose that container TEST1 is stoped or exited due to some reason you will get alerts on email as shown in image.

Thank you

Leave a comment