zabbix监控docker容器

1、环境说明

由于最近zabbix进行过一次迁移,所以zabbix-server系列采用docker方式安装,参考zabbix官网:https://github.com/zabbix/zabbix-docker。为适应本地环境和需求,docker-compose.yml文件有改动,具体内容如下:

docker-compose.yml文件

version: '3.5'
services:zabbix-server:image: zabbix/zabbix-server-mysql:centos-4.2-latestports:- "10051:10051"volumes:- /etc/localtime:/etc/localtime:ro- /etc/timezone:/etc/timezone:ro - ./zbx_env/usr/lib/zabbix/alertscripts:/usr/lib/zabbix/alertscripts:ro- ./zbx_env/usr/lib/zabbix/externalscripts:/usr/lib/zabbix/externalscripts:ro- ./zbx_env/var/lib/zabbix/modules:/var/lib/zabbix/modules:ro- ./zbx_env/var/lib/zabbix/enc:/var/lib/zabbix/enc:ro- ./zbx_env/var/lib/zabbix/ssh_keys:/var/lib/zabbix/ssh_keys:ro- ./zbx_env/var/lib/zabbix/mibs:/var/lib/zabbix/mibs:rolinks:- mysql-server:mysql-servercontainer_name: zabbix-serverrestart: unless-stoppedulimits:nproc: 65535nofile:soft: 20000hard: 40000env_file:- .env_db_mysql- .env_srvsecrets:- MYSQL_USER- MYSQL_PASSWORD- MYSQL_ROOT_PASSWORDuser: rootdepends_on:- mysql-serverstop_grace_period: 30ssysctls:- net.ipv4.ip_local_port_range=1024 65000- net.ipv4.conf.all.accept_redirects=0- net.ipv4.conf.all.secure_redirects=0- net.ipv4.conf.all.send_redirects=0zabbix-web-nginx-mysql:image: zabbix/zabbix-web-nginx-mysql:centos-4.2-latestports:- "8081:80"- "8443:443"links:- mysql-server:mysql-server- zabbix-server:zabbix-servercontainer_name: zabbix-web-nginx-mysqlrestart: unless-stoppedvolumes:- /etc/localtime:/etc/localtime:ro- /etc/timezone:/etc/timezone:ro- ./zbx_env/etc/ssl/nginx:/etc/ssl/nginx:roenv_file:- .env_db_mysql- .env_websecrets:- MYSQL_USER- MYSQL_PASSWORDuser: rootdepends_on:- mysql-server- zabbix-serverhealthcheck:test: ["CMD", "curl", "-f", "http://localhost"]interval: 10stimeout: 5sretries: 3start_period: 30sstop_grace_period: 10ssysctls:- net.core.somaxconn=65535zabbix-agent:image: zabbix/zabbix-agent:centos-4.2-latestports:- "10050:10050"volumes:- /etc/localtime:/etc/localtime:ro- /etc/timezone:/etc/timezone:ro- ./zbx_env/etc/zabbix/zabbix_agentd.d:/etc/zabbix/zabbix_agentd.d:ro- ./zbx_env/usr/lib/zabbix/alertscripts:/usr/lib/zabbix/alertscripts:ro- ./zbx_env/usr/lib/zabbix/externalscripts:/usr/lib/zabbix/externalscripts:ro- ./zbx_env/var/lib/zabbix/modules:/var/lib/zabbix/modules:ro- ./zbx_env/var/lib/zabbix/enc:/var/lib/zabbix/enc:ro- ./zbx_env/var/lib/zabbix/ssh_keys:/var/lib/zabbix/ssh_keys:rolinks:- zabbix-server:zabbix-serverrestart: unless-stoppedcontainer_name: zabbix-agentenv_file:- .env_agentuser: rootprivileged: truepid: "host"stop_grace_period: 5smysql-server:image: mysql:8.0ports:- "33060:3306"command: [mysqld, --character-set-server=utf8, --collation-server=utf8_bin, --default-authentication-plugin=mysql_native_password]volumes:- ./zbx_env/var/lib/mysql:/var/lib/mysql:rwrestart: unless-stoppedcontainer_name: mysql-serverenv_file:- .env_db_mysqlsecrets:- MYSQL_USER- MYSQL_PASSWORD- MYSQL_ROOT_PASSWORDuser: rootstop_grace_period: 1msecrets:MYSQL_USER:file: ./.MYSQL_USERMYSQL_PASSWORD:file: ./.MYSQL_PASSWORDMYSQL_ROOT_PASSWORD:file: ./.MYSQL_ROOT_PASSWORD
View Code

2、zabbix添加自定义监控

(1)zabbix_server.conf配置

#脚本路径
AlertScriptsPath=/usr/lib/zabbix/alertscripts ExternalScripts=/usr/lib/zabbix/externalscripts

(2)zabbix_agent.conf配置

##允许使用用户自定义参数
UnsafeUserParameters=1
##导入该文件下的配置
Include=/etc/zabbix/zabbix_agentd.d/*.conf

(3)自定义监控脚本

/usr/lib/zabbix/externalscripts/docker_discovery.py,搜集正在运行的容器的名称

#!/usr/bin/env python
# -*- coding: utf-8 -*
import os
import simplejson as json
t=os.popen("""docker ps |grep -v 'CONTAINER ID'|awk {'print $NF'} """)
container_name = []
for container in t.readlines():r = os.path.basename(container.strip())container_name += [{'{#CONTAINERNAME}':r}]
print(json.dumps({'data':container_name},sort_keys=True,indent=4,separators=(',',':')))
View Code

安装python3 所需要的包

pip3 install simplejson

docker_discovery.py执行结果

python3 docker_discovery.py
{"data":[{"{#CONTAINERNAME}":"nginx"},{"{#CONTAINERNAME}":"fortune"}]
}
View Code

/usr/lib/zabbix/externalscripts/docker_monitor.py,输入容器名称以及监控项,输出数据

#!/usr/bin/env python
import docker
import sys
import subprocess
import osdef check_container_stats(container_name,collect_item):if collect_item == "ping":cmd = 'docker inspect --format="{{.State.Running}}" %s' % container_nameresult = os.popen(cmd).read().replace("\n","")if result == "true":return 1else:return 0#:docker_client = docker_client.containers.get(container_name)container_collect=docker_client.containers.get(container_name).stats(stream=True)old_result=eval(next(container_collect))new_result=eval(next(container_collect))print(new_result)container_collect.close()if collect_item == 'cpu_total_usage':result=new_result['cpu_stats']['cpu_usage']['total_usage'] - old_result['cpu_stats']['cpu_usage']['total_usage']elif collect_item == 'cpu_system_usage':result=new_result['cpu_stats']['system_cpu_usage'] - old_result['cpu_stats']['system_cpu_usage']elif collect_item == 'cpu_percent':cpu_total_usage=new_result['cpu_stats']['cpu_usage']['total_usage'] - old_result['cpu_stats']['cpu_usage']['total_usage']cpu_system_uasge=new_result['cpu_stats']['system_cpu_usage'] - old_result['cpu_stats']['system_cpu_usage']cpu_num=len(old_result['cpu_stats']['cpu_usage']['percpu_usage'])result=round((float(cpu_total_usage)/float(cpu_system_uasge))*cpu_num*100.0,2)elif collect_item == 'mem_usage':result=new_result['memory_stats']['usage']elif collect_item == 'mem_limit':result=new_result['memory_stats']['limit']elif collect_item == 'network_rx_bytes':result=new_result['networks']['eth0']['rx_bytes']elif collect_item == 'network_tx_bytes':result=new_result['networks']['eth0']['tx_bytes']elif collect_item == 'mem_percent':mem_usage=new_result['memory_stats']['usage']mem_limit=new_result['memory_stats']['limit']result=round(float(mem_usage)/float(mem_limit)*100.0,2)return result
if __name__ == "__main__":docker_client = docker.DockerClient(base_url='unix://var/run/docker.sock')container_name=sys.argv[1]collect_item=sys.argv[2]print(check_container_stats(container_name,collect_item)
View Code

安装python3依赖的包

pip3 install docker

docker_monitor.py执行结果

python3 docker_monitor.py nginx mem_percent
0.49
View Code

(4)脚本赋执行权限

chmod +x docker_discovery.py
chmod +x docker_monitor.py

(5)自定义监控配置文件

/etc/zabbix/zabbix_agentd.d/docker_discovery.conf 
UserParameter=docker_discovery,/usr/bin/python3 /usr/lib/zabbix/externalscripts/docker_discovery.py
UserParameter=docker_status[*],/usr/bin/python3 /usr/lib/zabbix/externalscripts/docker_monitor.py $1 $2

 (6)导入模板

<?xml version="1.0" encoding="UTF-8"?>
<zabbix_export><version>4.2</version><date>2019-09-27T06:35:12Z</date><groups><group><name>Templates</name></group></groups><templates><template><template>Template Discovery Docker</template><name>Template Discovery Docker</name><description/><groups><group><name>Templates</name></group></groups><applications/><items/><discovery_rules><discovery_rule><name>collect docker container use resource</name><type>0</type><snmp_community/><snmp_oid/><key>docker_discovery</key><delay>30s</delay><status>0</status><allowed_hosts/><snmpv3_contextname/><snmpv3_securityname/><snmpv3_securitylevel>0</snmpv3_securitylevel><snmpv3_authprotocol>0</snmpv3_authprotocol><snmpv3_authpassphrase/><snmpv3_privprotocol>0</snmpv3_privprotocol><snmpv3_privpassphrase/><params/><ipmi_sensor/><authtype>0</authtype><username/><password/><publickey/><privatekey/><port/><filter><evaltype>0</evaltype><formula/><conditions><condition><macro>{#CONTAINERNAME}</macro><value/><operator>8</operator><formulaid>A</formulaid></condition></conditions></filter><lifetime>30d</lifetime><description/><item_prototypes><item_prototype><name>docker:{#CONTAINERNAME}:cpu_percent</name><type>0</type><snmp_community/><snmp_oid/><key>docker_status[{#CONTAINERNAME},cpu_percent]</key><delay>30s</delay><history>90d</history><trends>365d</trends><status>0</status><value_type>0</value_type><allowed_hosts/><units>%</units><snmpv3_contextname/><snmpv3_securityname/><snmpv3_securitylevel>0</snmpv3_securitylevel><snmpv3_authprotocol>0</snmpv3_authprotocol><snmpv3_authpassphrase/><snmpv3_privprotocol>0</snmpv3_privprotocol><snmpv3_privpassphrase/><params/><ipmi_sensor/><authtype>0</authtype><username/><password/><publickey/><privatekey/><port/><description/><inventory_link>0</inventory_link><applications/><valuemap/><logtimefmt/><preprocessing/><jmx_endpoint/><timeout>3s</timeout><url/><query_fields/><posts/><status_codes>200</status_codes><follow_redirects>1</follow_redirects><post_type>0</post_type><http_proxy/><headers/><retrieve_mode>0</retrieve_mode><request_method>0</request_method><output_format>0</output_format><allow_traps>0</allow_traps><ssl_cert_file/><ssl_key_file/><ssl_key_password/><verify_peer>0</verify_peer><verify_host>0</verify_host><application_prototypes/><master_item/></item_prototype><item_prototype><name>docker:{#CONTAINERNAME}:cpu_total_usage</name><type>0</type><snmp_community/><snmp_oid/><key>docker_status[{#CONTAINERNAME},cpu_total_usage]</key><delay>30s</delay><history>90d</history><trends>365d</trends><status>0</status><value_type>3</value_type><allowed_hosts/><units/><snmpv3_contextname/><snmpv3_securityname/><snmpv3_securitylevel>0</snmpv3_securitylevel><snmpv3_authprotocol>0</snmpv3_authprotocol><snmpv3_authpassphrase/><snmpv3_privprotocol>0</snmpv3_privprotocol><snmpv3_privpassphrase/><params/><ipmi_sensor/><authtype>0</authtype><username/><password/><publickey/><privatekey/><port/><description/><inventory_link>0</inventory_link><applications/><valuemap/><logtimefmt/><preprocessing/><jmx_endpoint/><timeout>3s</timeout><url/><query_fields/><posts/><status_codes>200</status_codes><follow_redirects>1</follow_redirects><post_type>0</post_type><http_proxy/><headers/><retrieve_mode>0</retrieve_mode><request_method>0</request_method><output_format>0</output_format><allow_traps>0</allow_traps><ssl_cert_file/><ssl_key_file/><ssl_key_password/><verify_peer>0</verify_peer><verify_host>0</verify_host><application_prototypes/><master_item/></item_prototype><item_prototype><name>docker:{#CONTAINERNAME}:men_percent</name><type>0</type><snmp_community/><snmp_oid/><key>docker_status[{#CONTAINERNAME},mem_percent]</key><delay>30s</delay><history>90d</history><trends>365d</trends><status>0</status><value_type>0</value_type><allowed_hosts/><units>%</units><snmpv3_contextname/><snmpv3_securityname/><snmpv3_securitylevel>0</snmpv3_securitylevel><snmpv3_authprotocol>0</snmpv3_authprotocol><snmpv3_authpassphrase/><snmpv3_privprotocol>0</snmpv3_privprotocol><snmpv3_privpassphrase/><params/><ipmi_sensor/><authtype>0</authtype><username/><password/><publickey/><privatekey/><port/><description/><inventory_link>0</inventory_link><applications/><valuemap/><logtimefmt/><preprocessing/><jmx_endpoint/><timeout>3s</timeout><url/><query_fields/><posts/><status_codes>200</status_codes><follow_redirects>1</follow_redirects><post_type>0</post_type><http_proxy/><headers/><retrieve_mode>0</retrieve_mode><request_method>0</request_method><output_format>0</output_format><allow_traps>0</allow_traps><ssl_cert_file/><ssl_key_file/><ssl_key_password/><verify_peer>0</verify_peer><verify_host>0</verify_host><application_prototypes/><master_item/></item_prototype><item_prototype><name>docker:{#CONTAINERNAME}:men_usage</name><type>0</type><snmp_community/><snmp_oid/><key>docker_status[{#CONTAINERNAME},mem_usage]</key><delay>30s</delay><history>90d</history><trends>365d</trends><status>0</status><value_type>0</value_type><allowed_hosts/><units>%</units><snmpv3_contextname/><snmpv3_securityname/><snmpv3_securitylevel>0</snmpv3_securitylevel><snmpv3_authprotocol>0</snmpv3_authprotocol><snmpv3_authpassphrase/><snmpv3_privprotocol>0</snmpv3_privprotocol><snmpv3_privpassphrase/><params/><ipmi_sensor/><authtype>0</authtype><username/><password/><publickey/><privatekey/><port/><description/><inventory_link>0</inventory_link><applications/><valuemap/><logtimefmt/><preprocessing/><jmx_endpoint/><timeout>3s</timeout><url/><query_fields/><posts/><status_codes>200</status_codes><follow_redirects>1</follow_redirects><post_type>0</post_type><http_proxy/><headers/><retrieve_mode>0</retrieve_mode><request_method>0</request_method><output_format>0</output_format><allow_traps>0</allow_traps><ssl_cert_file/><ssl_key_file/><ssl_key_password/><verify_peer>0</verify_peer><verify_host>0</verify_host><application_prototypes/><master_item/></item_prototype><item_prototype><name>docker:{#CONTAINERNAME}:network_rx_bytes</name><type>0</type><snmp_community/><snmp_oid/><key>docker_status[{#CONTAINERNAME},network_rx_bytes]</key><delay>30s</delay><history>90d</history><trends>365d</trends><status>0</status><value_type>0</value_type><allowed_hosts/><units>%</units><snmpv3_contextname/><snmpv3_securityname/><snmpv3_securitylevel>0</snmpv3_securitylevel><snmpv3_authprotocol>0</snmpv3_authprotocol><snmpv3_authpassphrase/><snmpv3_privprotocol>0</snmpv3_privprotocol><snmpv3_privpassphrase/><params/><ipmi_sensor/><authtype>0</authtype><username/><password/><publickey/><privatekey/><port/><description/><inventory_link>0</inventory_link><applications/><valuemap/><logtimefmt/><preprocessing/><jmx_endpoint/><timeout>3s</timeout><url/><query_fields/><posts/><status_codes>200</status_codes><follow_redirects>1</follow_redirects><post_type>0</post_type><http_proxy/><headers/><retrieve_mode>0</retrieve_mode><request_method>0</request_method><output_format>0</output_format><allow_traps>0</allow_traps><ssl_cert_file/><ssl_key_file/><ssl_key_password/><verify_peer>0</verify_peer><verify_host>0</verify_host><application_prototypes/><master_item/></item_prototype><item_prototype><name>docker:{#CONTAINERNAME}:network_tx_bytes</name><type>0</type><snmp_community/><snmp_oid/><key>docker_status[{#CONTAINERNAME},network_tx_bytes]</key><delay>30s</delay><history>90d</history><trends>365d</trends><status>0</status><value_type>0</value_type><allowed_hosts/><units>%</units><snmpv3_contextname/><snmpv3_securityname/><snmpv3_securitylevel>0</snmpv3_securitylevel><snmpv3_authprotocol>0</snmpv3_authprotocol><snmpv3_authpassphrase/><snmpv3_privprotocol>0</snmpv3_privprotocol><snmpv3_privpassphrase/><params/><ipmi_sensor/><authtype>0</authtype><username/><password/><publickey/><privatekey/><port/><description/><inventory_link>0</inventory_link><applications/><valuemap/><logtimefmt/><preprocessing/><jmx_endpoint/><timeout>3s</timeout><url/><query_fields/><posts/><status_codes>200</status_codes><follow_redirects>1</follow_redirects><post_type>0</post_type><http_proxy/><headers/><retrieve_mode>0</retrieve_mode><request_method>0</request_method><output_format>0</output_format><allow_traps>0</allow_traps><ssl_cert_file/><ssl_key_file/><ssl_key_password/><verify_peer>0</verify_peer><verify_host>0</verify_host><application_prototypes/><master_item/></item_prototype><item_prototype><name>docker:{#CONTAINERNAME}:is run</name><type>0</type><snmp_community/><snmp_oid/><key>docker_status[{#CONTAINERNAME},ping]</key><delay>30s</delay><history>90d</history><trends>365d</trends><status>0</status><value_type>0</value_type><allowed_hosts/><units>%</units><snmpv3_contextname/><snmpv3_securityname/><snmpv3_securitylevel>0</snmpv3_securitylevel><snmpv3_authprotocol>0</snmpv3_authprotocol><snmpv3_authpassphrase/><snmpv3_privprotocol>0</snmpv3_privprotocol><snmpv3_privpassphrase/><params/><ipmi_sensor/><authtype>0</authtype><username/><password/><publickey/><privatekey/><port/><description/><inventory_link>0</inventory_link><applications/><valuemap/><logtimefmt/><preprocessing/><jmx_endpoint/><timeout>3s</timeout><url/><query_fields/><posts/><status_codes>200</status_codes><follow_redirects>1</follow_redirects><post_type>0</post_type><http_proxy/><headers/><retrieve_mode>0</retrieve_mode><request_method>0</request_method><output_format>0</output_format><allow_traps>0</allow_traps><ssl_cert_file/><ssl_key_file/><ssl_key_password/><verify_peer>0</verify_peer><verify_host>0</verify_host><application_prototypes/><master_item/></item_prototype><item_prototype><name>docker:{#CONTAINERNAME}:cpu_system_usage</name><type>0</type><snmp_community/><snmp_oid/><key>docker_status[{#CONTAINERNAME},system_cpu_usage]</key><delay>30s</delay><history>90d</history><trends>365d</trends><status>0</status><value_type>0</value_type><allowed_hosts/><units>%</units><snmpv3_contextname/><snmpv3_securityname/><snmpv3_securitylevel>0</snmpv3_securitylevel><snmpv3_authprotocol>0</snmpv3_authprotocol><snmpv3_authpassphrase/><snmpv3_privprotocol>0</snmpv3_privprotocol><snmpv3_privpassphrase/><params/><ipmi_sensor/><authtype>0</authtype><username/><password/><publickey/><privatekey/><port/><description/><inventory_link>0</inventory_link><applications/><valuemap/><logtimefmt/><preprocessing/><jmx_endpoint/><timeout>3s</timeout><url/><query_fields/><posts/><status_codes>200</status_codes><follow_redirects>1</follow_redirects><post_type>0</post_type><http_proxy/><headers/><retrieve_mode>0</retrieve_mode><request_method>0</request_method><output_format>0</output_format><allow_traps>0</allow_traps><ssl_cert_file/><ssl_key_file/><ssl_key_password/><verify_peer>0</verify_peer><verify_host>0</verify_host><application_prototypes/><master_item/></item_prototype></item_prototypes><trigger_prototypes/><graph_prototypes><graph_prototype><name>docker:{#CONTAINERNAME}:cpu</name><width>900</width><height>200</height><yaxismin>0.0000</yaxismin><yaxismax>100.0000</yaxismax><show_work_period>1</show_work_period><show_triggers>1</show_triggers><type>0</type><show_legend>1</show_legend><show_3d>0</show_3d><percent_left>0.0000</percent_left><percent_right>0.0000</percent_right><ymin_type_1>0</ymin_type_1><ymax_type_1>0</ymax_type_1><ymin_item_1>0</ymin_item_1><ymax_item_1>0</ymax_item_1><graph_items><graph_item><sortorder>0</sortorder><drawtype>0</drawtype><color>1A7C11</color><yaxisside>0</yaxisside><calc_fnc>2</calc_fnc><type>0</type><item><host>Template Discovery Docker</host><key>docker_status[{#CONTAINERNAME},cpu_percent]</key></item></graph_item><graph_item><sortorder>1</sortorder><drawtype>0</drawtype><color>F63100</color><yaxisside>0</yaxisside><calc_fnc>2</calc_fnc><type>0</type><item><host>Template Discovery Docker</host><key>docker_status[{#CONTAINERNAME},system_cpu_usage]</key></item></graph_item><graph_item><sortorder>2</sortorder><drawtype>0</drawtype><color>2774A4</color><yaxisside>0</yaxisside><calc_fnc>2</calc_fnc><type>0</type><item><host>Template Discovery Docker</host><key>docker_status[{#CONTAINERNAME},cpu_total_usage]</key></item></graph_item></graph_items></graph_prototype><graph_prototype><name>docker:{#CONTAINERNAME}:menory</name><width>900</width><height>200</height><yaxismin>0.0000</yaxismin><yaxismax>100.0000</yaxismax><show_work_period>1</show_work_period><show_triggers>1</show_triggers><type>0</type><show_legend>1</show_legend><show_3d>0</show_3d><percent_left>0.0000</percent_left><percent_right>0.0000</percent_right><ymin_type_1>0</ymin_type_1><ymax_type_1>0</ymax_type_1><ymin_item_1>0</ymin_item_1><ymax_item_1>0</ymax_item_1><graph_items><graph_item><sortorder>0</sortorder><drawtype>0</drawtype><color>1A7C11</color><yaxisside>0</yaxisside><calc_fnc>2</calc_fnc><type>0</type><item><host>Template Discovery Docker</host><key>docker_status[{#CONTAINERNAME},mem_percent]</key></item></graph_item><graph_item><sortorder>1</sortorder><drawtype>0</drawtype><color>F63100</color><yaxisside>0</yaxisside><calc_fnc>2</calc_fnc><type>0</type><item><host>Template Discovery Docker</host><key>docker_status[{#CONTAINERNAME},mem_usage]</key></item></graph_item></graph_items></graph_prototype><graph_prototype><name>docker:{#CONTAINERNAME}:network</name><width>900</width><height>200</height><yaxismin>0.0000</yaxismin><yaxismax>100.0000</yaxismax><show_work_period>1</show_work_period><show_triggers>1</show_triggers><type>0</type><show_legend>1</show_legend><show_3d>0</show_3d><percent_left>0.0000</percent_left><percent_right>0.0000</percent_right><ymin_type_1>0</ymin_type_1><ymax_type_1>0</ymax_type_1><ymin_item_1>0</ymin_item_1><ymax_item_1>0</ymax_item_1><graph_items><graph_item><sortorder>0</sortorder><drawtype>0</drawtype><color>1A7C11</color><yaxisside>0</yaxisside><calc_fnc>2</calc_fnc><type>0</type><item><host>Template Discovery Docker</host><key>docker_status[{#CONTAINERNAME},network_rx_bytes]</key></item></graph_item><graph_item><sortorder>1</sortorder><drawtype>0</drawtype><color>F63100</color><yaxisside>0</yaxisside><calc_fnc>2</calc_fnc><type>0</type><item><host>Template Discovery Docker</host><key>docker_status[{#CONTAINERNAME},network_tx_bytes]</key></item></graph_item></graph_items></graph_prototype></graph_prototypes><host_prototypes/><jmx_endpoint/><timeout>3s</timeout><url/><query_fields/><posts/><status_codes>200</status_codes><follow_redirects>1</follow_redirects><post_type>0</post_type><http_proxy/><headers/><retrieve_mode>0</retrieve_mode><request_method>0</request_method><allow_traps>0</allow_traps><ssl_cert_file/><ssl_key_file/><ssl_key_password/><verify_peer>0</verify_peer><verify_host>0</verify_host><lld_macro_paths/><preprocessing/><master_item/></discovery_rule></discovery_rules><httptests/><macros/><templates/><screens/><tags/></template></templates>
</zabbix_export>
View Code

模板导入成功后,查看监控项是否可用,注意客户端版本是否和文章一致,这里的zabbix所有版本均为4.2,若有问题可留言讨论。

3、问题整理

由于原本客户端python是2.7版本,在执行docker_monitor.py时有如下报错,后来知道是python版本问题,升级python3以后执行成功。

# python docker_monitor.py
Traceback (most recent call last):File "docker_monitor.py", line 36, in
<module>docker_client = docker.DockerClient(base_url='unix://var/run/docker.sock') AttributeError: 'module' object has no attribute 'DockerClient'

(1)python2升级步骤

#安装python3.6
yum -y install epel-release
yum install https://centos7.iuscommunity.org/ius-release.rpm ##安装centos7的ius源
yum install python36u -y ln -s /usr/bin/python3.6 /bin/python3 #安装pip3 yum install python36u-pip -y ln -s /usr/bin/pip3.6 /bin/pip3 pip3 install --upgrade pip ##有些情况安装完python3之后就不需要再安装pip3

(2)升级python3后,simplejson和docker-py需要重装

pip3 install simplejson
#docker-py最新版改名为docker
pip3 install docker

(3)zabbix-serve端测试时报错

zabbix_get -s 10.8.0.22 -p 10050 -k  docker_status[reids,cpu_percent]
Traceback (most recent call last):File "/usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py", line 672, in urlopenchunked=chunked,File "/usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py", line 387, in _make_requestconn.request(method, url, **httplib_request_kw)File "/usr/lib64/python3.6/http/client.py", line 1254, in requestself._send_request(method, url, body, headers, encode_chunked)File "/usr/lib64/python3.6/http/client.py", line 1300, in _send_requestself.endheaders(body, encode_chunked=encode_chunked)File "/usr/lib64/python3.6/http/client.py", line 1249, in endheadersself._send_output(message_body, encode_chunked=encode_chunked)File "/usr/lib64/python3.6/http/client.py", line 1036, in _send_outputself.send(msg)File "/usr/lib64/python3.6/http/client.py", line 974, in sendself.connect()File "/usr/local/lib/python3.6/site-packages/docker/transport/unixconn.py", line 43, in connectsock.connect(self.unix_socket)
PermissionError: [Errno 13] Permission deniedDuring handling of the above exception, another exception occurred:Traceback (most recent call last):File "/usr/local/lib/python3.6/site-packages/requests/adapters.py", line 449, in sendtimeout=timeoutFile "/usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py", line 720, in urlopenmethod, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2]File "/usr/local/lib/python3.6/site-packages/urllib3/util/retry.py", line 400, in incrementraise six.reraise(type(error), error, _stacktrace)File "/usr/local/lib/python3.6/site-packages/urllib3/packages/six.py", line 734, in reraiseraise value.with_traceback(tb)File "/usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py", line 672, in urlopenchunked=chunked,File "/usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py", line 387, in _make_requestconn.request(method, url, **httplib_request_kw)File "/usr/lib64/python3.6/http/client.py", line 1254, in requestself._send_request(method, url, body, headers, encode_chunked)File "/usr/lib64/python3.6/http/client.py", line 1300, in _send_requestself.endheaders(body, encode_chunked=encode_chunked)File "/usr/lib64/python3.6/http/client.py", line 1249, in endheadersself._send_output(message_body, encode_chunked=encode_chunked)File "/usr/lib64/python3.6/http/client.py", line 1036, in _send_outputself.send(msg)File "/usr/lib64/python3.6/http/client.py", line 974, in sendself.connect()File "/usr/local/lib/python3.6/site-packages/docker/transport/unixconn.py", line 43, in connectsock.connect(self.unix_socket)
urllib3.exceptions.ProtocolError: ('Connection aborted.', PermissionError(13, 'Permission denied'))During handling of the above exception, another exception occurred:Traceback (most recent call last):File "/usr/lib/zabbix/externalscripts/docker_monitor.py", line 39, in <module>print(check_container_stats(container_name,collect_item))File "/usr/lib/zabbix/externalscripts/docker_monitor.py", line 9, in check_container_statscontainer_collect=docker_client.containers.get(container_name).stats(stream=True)File "/usr/local/lib/python3.6/site-packages/docker/models/containers.py", line 880, in getresp = self.client.api.inspect_container(container_id)File "/usr/local/lib/python3.6/site-packages/docker/utils/decorators.py", line 19, in wrappedreturn f(self, resource_id, *args, **kwargs)File "/usr/local/lib/python3.6/site-packages/docker/api/container.py", line 756, in inspect_containerself._get(self._url("/containers/{0}/json", container)), TrueFile "/usr/local/lib/python3.6/site-packages/docker/utils/decorators.py", line 46, in innerreturn f(self, *args, **kwargs)File "/usr/local/lib/python3.6/site-packages/docker/api/client.py", line 230, in _getreturn self.get(url, **self._set_request_timeout(kwargs))File "/usr/local/lib/python3.6/site-packages/requests/sessions.py", line 546, in getreturn self.request('GET', url, **kwargs)File "/usr/local/lib/python3.6/site-packages/requests/sessions.py", line 533, in requestresp = self.send(prep, **send_kwargs)File "/usr/local/lib/python3.6/site-packages/requests/sessions.py", line 646, in sendr = adapter.send(request, **kwargs)File "/usr/local/lib/python3.6/site-packages/requests/adapters.py", line 498, in sendraise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', PermissionError(13, 'Permission denied'))
View Code

从错误可以看出是权限问题,解决办法:

#查看docker.sock用户权限
ls /var/run/docker.sock -lh
srw-rw---- 1 root docker 0 9月   2 17:04 /var/run/docker.sock
#将zabbix用户加入docker所在组
gpasswd -a zabbix docker

zabbix_get测试连接

 zabbix_get -s 10.8.0.22 -p 10050 -k  docker_status[redis,mem_percent]
0.3

以上所有内容均为亲自测试成功后才写的,那些踩的最深的坑都已经都修改,大可放心使用。

 

转载于:https://www.cnblogs.com/wanghongli/p/11598121.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/361362.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Hibernate应用程序级可重复读取

介绍 在我以前的文章中&#xff0c;我描述了应用程序级事务如何为长时间的对话提供合适的并发控制机制。 所有实体都在Hibernate会话的上下文中加载&#xff0c;充当事务后写式缓存 。 Hibernate持久性上下文可以包含给定实体的一个引用和一个引用。 一级缓存可确保会话级可重…

canvas动画简单操作

canvas动画 小球滚动效果 关键api&#xff1a; window.requestAnimationFrame(draw) 会递归调用draw函数&#xff0c;替代setIntervalvar x 20; var speed 4; //电脑的帧率是1秒钟60Hz&#xff0c; 就相当于一秒钟可以播放60张图片&#xff0c;就相当于播放一张图片使用16.…

使用PrimeFaces开发数据导出实用程序

我的日常工作涉及大量使用数据。 我们使用关系数据库来存储所有内容&#xff0c;因为我们依赖于企业级的数据管理。 有时&#xff0c;具有将数据提取为简单格式&#xff08;例如电子表格&#xff09;的功能很有用&#xff0c;以便我们可以按需进行操作。 这篇文章概述了我使用P…

Tomcat到Wildfly:配置数据库连接

此摘录摘自《 从Tomcat到WildFly 》一书&#xff0c;您将在其中学习如何将现有的Tomcat体系结构移植到WildFly&#xff0c;包括服务器配置和在其顶部运行的应用程序。 WildFly是完全兼容的Java Enterprise Edition 7容器&#xff0c;与Tomcat相比&#xff0c;它具有更多的可用…

在jOOQ之上构建的RESTful JDBC HTTP服务器

jOOQ生态系统和社区正在持续增长。 我们个人总是很高兴看到基于jOOQ构建的其他开源项目。 今天&#xff0c;我们非常高兴为您介绍BjrnHarrtell结合REST和RDBMS的一种非常有趣的方法。 BjrnHarrtell从小就是瑞典的程序员。 他通常在Sweco Position AB上忙于编写GIS系统和集成&a…

node.js 搭建http调取 mysql数据库中的值

首先&#xff0c;我们先在数据库中创建两个表t_news,t_news_type;插入数据&#xff1a; 然后我们再写代码&#xff1a; //加载模块express var express require("express"); var fs require("fs"); //加载路径 var url require("url"); //加…

NHibernate.3.0.Cookbook第三章第9节的翻译

Using stateless sessions 使用无状态会话 当进行大量数据处理的时候,可能会放弃使用一些高级特性,而使用更接近底层的API来提高性能.在NHibernate中,这种高性能的底层API就是无状态的会话.本节介绍如何使用无状态会话来更新movie对象的价格. 准备 使用第一章的Eg.Core和第二章…

致电以验证您的JavaFX UI的响应能力

最近&#xff0c;Jim Weaver在他的Surface Pro上为演示安装了我的小图片索引应用“ picmodo”&#xff0c;并且GUI变成了垃圾。 显然&#xff0c;Windows Tablet上JavaFX的基本字体大小很高&#xff1a; 我认为&#xff0c;即使调整大小行为和预期一样工作&#xff0c;UI也绝…

vuex 管理vue-router的传值

假设有这样的一种情况&#xff0c;在两个组件中。一个组件【A】主要是比如说放表格数据&#xff0c;而另外一个组件【B】是专门用来向组件A的表格添加数据的表单。这个时候就是两个兄弟组件之间传递数据了。首先想到的是使用兄弟组件传递数据的方法&#xff1a; 新建一个中间件…

c++ 错误处理

void __fastcall TForm1::Button1Click(TObject *Sender) { try { int iEdit1->Text.ToInt(); Edit1->TextAnsiString(10/i); } catch (...) { ShowMessage("Error"); } } 通过 为知笔记 发布转载于:https://www.cnblogs.com/xe2011/archive/2012/07/16/55298e…

前后端分手大师——MVVM 模式

阅读目录简而言之组成部分没有什么是一个栗子不能解决的简而言之 之前对 MVVM 模式一直只是模模糊糊的认识&#xff0c;正所谓没有实践就没有发言权&#xff0c;通过这两年对 Vue 框架的深入学习和项目实践&#xff0c;终于可以装B了有了拨开云雾见月明的感觉。 Model–View–…

Java性能调优调查结果(第三部分)

这是该系列文章的第三篇&#xff0c;我们将分析2014年10月进行的调查的结果。如果您尚未这样做&#xff0c;我建议从该系列的前两篇文章开始&#xff1a; 问题严重性分析和监视域分析 。 这篇文章着重于故障排除/根本原因检测。 本调查部分的背景&#xff1a;意识到性能问题并…

划分树

昨天的杭电多校联合训练热身赛的一道题&#xff0c;求区间的中位数&#xff0c;快排会超时&#xff0c;划分树的模版题。。 划分树是一种基于线段树的数据结构。主要用于快速求出(在log(n)的时间复杂度内&#xff09;序列区间的第k大值 。划分树和归并树都是用线段树作为辅助的…

Canvas事件绑定

canvas事件绑定 众所周知canvas是位图&#xff0c;在位图里我们可以在里面画各种东西&#xff0c;可以是图片&#xff0c;可以是线条等等。那我们想给canvas里的某一张图片添加一个点击事件该怎么做到。而js只能监听到canvas的事件&#xff0c;很明显这个图片是不存在与dom里面…

控件注册 - 利用资源文件将dll、ocx打包进exe文件(转)

很多时候自定义或者引用控件都需要注册才能使用&#xff0c;但是如何使要注册的dll或ocx打包到exe中&#xff0c;使用户下载以后看到的只是一个exe,点击直接运行呢&#xff1f;就像很多安全控件&#xff0c;如支付宝的aliedit.exe那样。 现在介绍一种使用资源文件&#xff0c;将…

Canvas-图片旋转

Canvas-图片旋转 众所周知canvas是位图&#xff0c;你可以在里面渲染你要的东西&#xff0c;不过你只能操作canvas的属性来进行编辑。就是说你并不能操作画进canvas的东西&#xff0c;例如我在canvas里添加一幅画&#xff0c;我现在想将那幅画移动10px&#xff0c;我们并不能直…

CSS3实现多页签图片缩放切换效果

多页签切换效果&#xff0c;图片缩放&#xff0c;鼠标移动到图片上后显示文字内容等等&#xff0c;效果很集中呐 截图如下&#xff1a; 下载地址&#xff1a;http://www.lanrenzhijia.com/js/css3/2012/0718/602.html 预览地址&#xff1a;http://www.lanrenzhijia.com/yulan/2…

Angular使用总结 --- 如何正确的操作DOM

无奈接手了一个旧项目&#xff0c;上一个老哥在Angular项目中大量使用了JQuery来操作DOM&#xff0c;真的是太不讲究了。那么如何优雅的使用Angular的方式来操作DOM呢&#xff1f; 获取元素 1、ElementRef --- A wrapper around a native element inside of a View. 在组件…

非首屏图片延时加载

目标 减少资源加载可以明显的优化页面加载的速度&#xff0c;所以可以减少页面载入时立即下载的图片的数量&#xff0c;以提高页面加载速度&#xff0c;其他的图片在需要的时候再进行加载。 思路 想要实现以上的目标&#xff0c;有几个地方需要思考。 1、如何判断哪些图片需要…

具有链接资源的Spring RestTemplate

Spring Data REST是一个了不起的项目&#xff0c;它提供了一些机制来将基于Spring Data的存储库中的资源公开为REST资源。 使用链接资源公开服务 考虑两个简单的基于JPA的实体&#xff0c;课程和教师&#xff1a; Entity Table(name "teachers") public class Tea…