Zabbix monitors docker containers through scripts

One, prepare one zabbix server, one monitored machine, and install zabbix_agentd and docker services on the monitored machine.

The ip of my docker machine here is 192.168.4.10, and the hostname is docker. (The zabbix version I installed is 3.4.4, docker version: docker-ce 18.06.1)

Second, modify the configuration in zabbix_agentd.conf on the docker machine as follows:

# vim /usr/local/etc/zabbix_agentd.conf

       UnsafeUserParameters=1

       UserParameter=docker.discovery,/usr/local/zabbix/script/docker.py

       UserParameter=docker.[*],/usr/local/zabbix/script/docker.py $1 $2

Third, write the following code into /usr/local/zabbix/script/docker.py, and add permissions to the script

        #  vim /usr/local/zabbix/script/docker.py

        # chmod 777 /usr/local/zabbix/script/docker.py

#!/usr/bin/python
import sys
import os
import json


def discover():
    d = {}
    d['data'] = []
    with os.popen("sudo docker ps -a --format {
   
   {.Names}}") as pipe:
        for line in pipe:
            info = {}
            info['{#CONTAINERNAME}'] = line.replace("\n","")
            d['data'].append(info)

    print json.dumps(d)


def status(name,action):
    if action == "ping":
        cmd = 'sudo docker inspect --format="{
   
   {.State.Running}}" %s' %name
        result = os.popen(cmd).read().replace("\n","")
        if result == "true":
            print 1
        else:
            print 0
    else:
        cmd = 'sudo docker stats %s --no-stream --format "{
   
   {.%s}}"' % (name,action)
        result = os.popen(cmd).read().replace("\n","")
        if "%" in result:
            print float(result.replace("%",""))
        else:
            print result


if __name__ == '__main__':
        try:
                name, action = sys.argv[1], sys.argv[2]
                status(name,action)
        except IndexError:
                discover()

Fourth, execute the command visudo to add the following content:

zabbix ALL=(ALL) NOPASSWD:/usr/bin/docker

      # python /usr/local/zabbix/script/docker.py Test whether the script can be executed normally. Normally, you should be able to get the container in docker, and the result is in json format.

After configuring the above, you can restart zabbix_agentd first

Test whether the key can be executed successfully through the zabbix_get command

# zabbix_get -s 127.0.0.1 -k 'docker.[nginx,CPUPerc]'

At this point, the zabbix_agent terminal is ready, and then add templates and monitoring items on the zabbix management page.

Five, page configuration

First add the corresponding docker host

Create a new template

Add app set

Add auto-discovery rules

Add new item prototype

Add cpu and mem two monitoring prototypes

Link the docker host to the new template

After a while, you should be able to see the monitored data in the latest data.

Guess you like

Origin blog.csdn.net/weixin_42182501/article/details/114641062