Understanding and Implementing Zabbix for System Monitoring

Zabbix is an enterprise-grade open-source monitoring solution renowned for its ability to track the performance and availability of servers, networks, and applications. Before delving into Zabbix's specifics, it's beneficial to understand foundational monitoring concepts, particularly the Simple Network Management Protocol (SNMP), and to compare Zabbix with other established tools like Cacti and Nagios.

Fundamentals of SNMP Monitoring

SNMP, or Simple Network Management Protocol, is a widely used protocol for managing and monitoring network devices and their attached systems. It operates with two primary components:

  • Management Station (NMS): The centralized monitoring server.
  • Agent: Software running on the monitored device.

SNMP supports two main modes of data exchange:

  • Polling (Active Mode): The NMS actively requests data from agents.
  • Traps (Passive Mode): Agents send unsolicited notifications (traps) to the NMS when specific events occur.

Key SNMP components include:

  • Management Information Base (MIB): A hierarchical database that defines the characteristics of objects that can be managed on a network device. Agents expose their data through MIBs.
  • Structure of Management Information (SMI): Specifies the rules for describing MIB objects.
  • SNMP Protocol: The communication standard itself, operating primarily over UDP ports 161 (for NMS polling) and 162 (for agent traps).

SNMP operations initiated by the NMS include:

  • Get: Retrieve the value of a single MIB object.
  • GetNext: Retrieve the value of the next MIB object in the hierarchy.
  • Set: Modify the value of a MIB object (allowing configuration changes).
  • Trap: An asynchronous notification sent by the agent to the NMS.

SNMP has evolved through several versions:

  • SNMPv1: Basic, lacks authentication and encryption.
  • SNMPv2c: Improves on v1 with more data types and enhanced error handling, but still uses community strings for authentication (no strong security).
  • SNMPv3: Introduces robust security features including authentication, privacy (encryption), and message integrity. Despite its advanced features, v1 and v2c are still commonly deployed due to their simplicity.

MIBs can be structured into "views," which are subsets of the full MIB tree, allowing administrators to define specific permissions (read-only or read-write) for different community strings or users.

Zabbix in the Monitoring Landscape: Cacti vs. Nagios

Historically, organizations often combined monitoring tools like Cacti and Nagios to cover different needs. Zabbix emerged as a comprehensive solution aiming to integrate the strengths of both.

Cacti: Data Visualization Powerhouse

Cacti excels at data collection and visualization. It frequently uses SNMP to gather data from various devices, stores this data in a specialized Round Robin Database (RRD), and then leverages PHP to generate detailed, real-time graphs. While Cacti offers powerful charting and can define thresholds for basic alerts, its native alerting capabilities are often considered weak and less dynamic, especially for critical service state changes.

RRD is a unique database that stores data in a fixed-size ring buffer. Once the buffer is full, new data overwrites the oldest data. This characteristic makes RRD efficient for storing time-series data without indefinite growth, but it requires careful planning for data retention policies.

Nagios: Alerting Champion

Nagios is renowned for its robust and flexible alerting mechanisms. It can be configured to detect threshold breaches, transition between "soft" (initial detection) and "hard" (persistent issue) states, and trigger a wide array of notifications, including emails, SMS, or custom scripts. However, Nagios can become less efficient and challenging to scale in very large, distributed environments with hundreds or thousands of monitored hosts and metrics, as it lacks built-in distributed processing capabilities.

Zabbix: The Unified Solution

Zabbix integrates the strengths of Cacti's data collection and visualization with Nagios's powerful alerting. It offers:

  • Comprehensive Data Collection: Via its own Zabbix Agent, SNMP, SSH, IPMI, HTTP/HTTPS, and custom scripts.
  • Flexible Data Storage: Supports traditional relational databases like MySQL, PostgreSQL, Oracle, SQLite, and DB2. This allows for persistent data storage and flexible data retention policies, unlike RRD's fixed-size nature.
  • Rich Visualization: Built-in graphing, dashboards, and maps for presenting collected data.
  • Powerful Alerting: Configurable triggers, severity levels, and various notification methods (email, SMS, custom scripts, webhooks).
  • Scalability and Distribution: Designed for large-scale environments, supporting tens of thousands of devices and hundreds of thousands of metrics, with built-in proxy capabilities for distributed monitoring.

Zabbix Overview and Architecture

Zabbix is an open-source, enterprise-level monitoring platform capable of handling vast monitoring infrastructures. It provides comprehensive monitoring for servers, virtual machines, network devices, cloud resources, databases, web applications, and more.

Key Monitoring Areas:

  1. Hardware/Software Status: Routers, switches, servers, operating systems, applictaions.
  2. Availability: Service uptime, host reachability.
  3. Performance Metrics: CPU utilization, memory usage, disk I/O, network traffic.
  4. Trend Analysis: Long-term data collection for capacity planning and performance trending.
  5. Event Management: Log file monitoring, specific event detection.

Distributed Monitoring with Zabbix Proxy:

For very large or geographically dispersed environments, Zabbix employs a proxy component. A Zabbix proxy collects monitoring data from agents within its local network segment and then forwards it to the central Zabbix server. This reduces the load on the Zabbix server and minimizes network traffic between remote sites and the central server. The proxy buffers data locally if the connection to the server is interrupted, ensuring no data loss.

Zabbix Core Components:

  • Zabbix Server: The central daemon that performs monitoring, data collection, and calculations. It's written in C.
  • Zabbix Agent: Lightweight software deployed on target hosts to actively collect local data and send it to the Zabbix server or proxy. Also written in C.
  • Zabbix Database: Stores all configuration data, historical metrics, event data, and trends. Supports MySQL, PostgreSQL, Oracle, IBM DB2, and SQLite.
  • Zabbix Web Interface (GUI): A PHP-based front-end for configuring Zabbix, managing items, triggers, and templates, and visualizing monitoring data through graphs, dashboards, and maps.
  • Zabbix Proxy: An optional, independent daemon that collects performance and availability data on behalf of the Zabbix server.

Key Zabbix Server Processes:

  • Pollers: Collect data from Zabbix agents, SNMP agents, and other services. Multiple pollers can be run concurrently.
  • HTTP Pollers: Specialized pollers for monitoring web scenarios and HTTP services.
  • Discoverers: Responsible for network dicsovery and low-level discovery operations.
  • Alerters: Send notifications based on configured actions and triggers.
  • Housekeepers: Maintain database integrity by removing old historical and trend data according to retention policies.
  • Watchdogs: Monitor other Zabbix processes to ensure they are running.
  • Escalators: Manage the escalation of alerts based on defined actions.
  • Timers: Execute time-based functions.
  • Pinger: Performs ICMP pings to check host availability.
  • DB Syncers: (Db_config_syncer, Db_data_syncer) Manage synchronization of configuration and historical data in distributed setups.

Hardware Sizing and Data Storage Considerations

Effective Zabbix deployment requires appropriate hardware sizing for the server and database, especially considering the volume of data to be stored.

Hardware Recommendations (Examples):

  • Small (up to 20 hosts): Pentium II 350MHz, 256MB RAM, SQLite.
  • Medium (up to 500 hosts): AMD Athlon 3200+, 2GB RAM, MySQL (InnoDB).
  • Large (up to 1000 hosts): Intel Core 6300+, 4GB RAM, RAID 10 MySQL (InnoDB) or PostgreSQL.
  • Very Large (over 1000 hosts): Xeon dual-CPU, 8GB RAM, Fast RAID 10 MySQL (InnoDB) or PostgreSQL.

Estimating Database Storage:

Zabbix stores several types of data, each contributing to the overall storage footprint:

  • Configuration Data: Relatively small, grows with item/host count.
  • History Data: Approximately 50 bytes per value.
  • History Trend Data: Approximately 128 bytes per aggregated trend value.
  • Event Data: Approximately 130 bytes per event.

To estimate storage, consider the number of items, their update intervals, and the data retention period. For example, if an item collects data every 5 minutes and is stored for 30 days, you can calculate the total bytes per item over the retention period and multiply by the number of items.

Zabbix Server and Agent Installation (on CentOS/RHEL 6.x)

This guide demonstrates a typical installation process for Zabbix server, web interface, and agent, using MariaDB as the backend database.

1. Database Setup (MariaDB)

First, install MariaDB (or MySQL) and create the necessary database and user for Zabbix.

# Install essential build tools
yum groupinstall "Development Tools" "Server Platform Development" -y
yum -y install cmake

# Create system user and group for MariaDB
groupadd -r -g 306 mysql
useradd -r -g 306 -u 306 mysql

# Download and extract MariaDB (e.g., mariadb-5.5.44.tar.gz)
tar xf mariadb-5.5.44.tar.gz
cd mariadb-5.5.44

# Compile and install MariaDB
# Note: Adjust installation prefix as needed.
cmake \
    -DCMAKE_INSTALL_PREFIX=/usr/local/mariadb-5.5.44 \
    -DMYSQL_DATADIR=/mydata/data \
    -DSYSCONFDIR=/etc \
    -DWITH_INNOBASE_STORAGE_ENGINE=1 \
    -DWITH_ARCHIVE_STORAGE_ENGINE=1 \
    -DWITH_BLACKHOLE_STORAGE_ENGINE=1 \
    -DWITH_READLINE=1 \
    -DWITH_SSL=system \
    -DWITH_ZLIB=system \
    -DWITH_LIBWRAP=0 \
    -DMYSQL_UNIX_ADDR=/tmp/mysql.sock \
    -DDEFAULT_CHARSET=utf8 \
    -DDEFAULT_COLLATION=utf8_general_ci

make
make install

# Initialize data directory and configure
mkdir /mydata/data # Ensure this directory exists
cd /usr/local/mariadb-5.5.44/
scripts/mysql_install_db --user=mysql --datadir=/mydata/data

# Copy configuration and service scripts
cp support-files/my-large.cnf /etc/my.cnf # Use a suitable config
cp support-files/mysql.server /etc/init.d/mysqld
chmod +x /etc/init.d/mysqld
chkconfig --add mysqld
chkconfig mysqld on

# Edit MariaDB configuration for data directory and optimization
# Example additions to /etc/my.cnf under [mysqld] section:
# datadir = /mydata/data
# innodb_file_per_table = 1
# skip_name_resolve = 1 # Recommended for performance if DNS is not critical

# Start MariaDB service
service mysqld start

# Secure MariaDB installation (set root password, remove anonymous users, etc.)
/usr/local/mariadb-5.5.44/bin/mysql_secure_installation

# Add MariaDB binaries to system PATH
echo 'export PATH=/usr/local/mariadb-5.5.44/bin:$PATH' > /etc/profile.d/mariadb.sh
. /etc/profile.d/mariadb.sh

# Create Zabbix database and user
mysql -uroot -p # Enter MariaDB root password

MariaDB [(none)]> CREATE DATABASE zabbix CHARACTER SET utf8 COLLATE utf8_bin;
MariaDB [(none)]> GRANT ALL PRIVILEGES ON zabbix.* TO 'zabbix_user'@'localhost' IDENTIFIED BY 'secure_password';
MariaDB [(none)]> GRANT ALL PRIVILEGES ON zabbix.* TO 'zabbix_user'@'172.16.%.%' IDENTIFIED BY 'secure_password'; # For remote access if needed
MariaDB [(none)]> FLUSH PRIVILEGES;
MariaDB [(none)]> EXIT;

2. Zabbix Server and Agent Installation

We'll use Zabbix's official repository for easier installation.

# Download Zabbix repository RPM (adjust version as needed, e.g., 2.4 for this guide)
wget http://repo.zabbix.com/zabbix/2.4/rhel/6/x86_64/zabbix-release-2.4-1.el6.noarch.rpm
rpm -ivh zabbix-release-2.4-1.el6.noarch.rpm

# Install Zabbix server, web interface, and agent packages
yum install -y zabbix-server-mysql zabbix-web-mysql zabbix-agent

# Import Zabbix database schema (ensure you're in the correct directory)
cd /usr/share/doc/zabbix-server-mysql-2.4.5/create/ # Adjust version path
mysql -uzabbix_user -psecure_password zabbix < schema.sql
mysql -uzabbix_user -psecure_password zabbix < images.sql
mysql -uzabbix_user -psecure_password zabbix < data.sql

3. Configure Zabbix Server

Edit the Zabbix server configuration file: /etc/zabbix/zabbix_server.conf.

# Essential database settings
DBHost=localhost
DBName=zabbix
DBUser=zabbix_user
DBPassword=secure_password
DBSocket=/tmp/mysql.sock # Or /var/lib/mysql/mysql.sock depending on MariaDB config

# Other important settings (uncomment and adjust as needed)
# LogFileSize=0
# DebugLevel=3
# StartPollers=5
# StartDiscoverers=1
# StartTimers=1
# MaxHousekeeperDelete=500
# AlertScriptsPath=/usr/lib/zabbix/alertscripts
# ExternalScripts=/usr/lib/zabbix/externalscripts

Start the Zabbix server:

service zabbix-server start
chkconfig zabbix-server on

4. Configure Zabbix Web Interface (PHP Frontend)

Zabbix web interface typically uses Apache HTTP Server. You'll find a Zabbix configuration file in Apache's conf.d directory (e.g., /etc/httpd/conf.d/zabbix.conf).

Adjust PHP settings in /etc/php.ini, especially the timezone:

date.timezone = Asia/Shanghai # Or your local timezone

Restart Apache for changes to take effect:

service httpd restart

Access the Zabbix web interface by navigating to http://<your_zabbix_server_ip>/zabbix in your browser. Follow the on-screen instructions for the final setup. The default credentials are Admin / zabbix.

Troubleshooting Database Socket Error: If you encounter "Error connecting to database: Can't connect to local MySQL server through socket", it usually means the Zabbix server and MariaDB are looking for the socket file in different locations. Create a symbolic link:

# Example for a common scenario if MariaDB uses /tmp/mysql.sock and Zabbix expects /var/lib/mysql/mysql.sock
ln -s /tmp/mysql.sock /var/lib/mysql/mysql.sock

5. Configure Zabbix Agent (Self-monitoring)

To monitor the Zabbix server itself, configure its agent:

vim /etc/zabbix/zabbix_agentd.conf

Modify the following parameters:

Server=127.0.0.1,172.16.249.22 # Zabbix server IP (or comma-separated list of IPs allowed to poll this agent)
ServerActive=172.16.249.22 # Zabbix server IP for active checks (agent sends data to server)
Hostname=Zabbix_Server_Host # Unique hostname for this agent

Start the Zabbix agent:

service zabbix-agent start
chkconfig zabbix-agent on

6. Monitoring a Remote Host

To monitor a remote host (e.g., PC1), install and configure the Zabbix agent on it:

# On PC1:
yum install -y zabbix-agent

vim /etc/zabbix/zabbix_agentd.conf

Configure agent on PC1:

Server=172.16.249.22 # Zabbix server IP
ServerActive=172.16.249.22 # Zabbix server IP for active checks
Hostname=PC1 # Unique hostname for this agent

Start the agent on PC1:

service zabbix-agent start
chkconfig zabbix-agent on

Firewall: Ensure that the Zabbix server (port 10050) and agent (port 10051) ports are open in any firewalls (e.g., iptables, firewalld) between the server and the monitored host.

In the Zabbix web GUI, navigate to Configuration > Hosts and click "Create host." Enter the Host name (matching Hostname in agent config), Visible name, IP address, and link relevant templates (e.g., "Template OS Linux" for a Linux server).

Specific Monitoring Examples

1. Monitoring MySQL Service Status

You can monitor basic MySQL service availability using a UserParameter in the Zabbix agent configuration.

# On the MySQL server (where agent is installed):
vim /etc/zabbix/zabbix_agentd.conf

Add the following line:

UserParameter=mysql.status.alive,mysqladmin ping | grep -c alive

Restart the Zabbix agent:

service zabbix-agent restart

Test the UserParameter from the Zabbix server:

zabbix_get -s <MySQL_SERVER_IP> -p 10050 -k "mysql.status.alive"
# Expected output: 1 (if MySQL is running), 0 (if not)

In Zabbix Web GUI:

  1. Create Item: Go to Configuration > Hosts, select your MySQL host, then Items > Create item.
    • Name: MySQL Service Status
    • Type: Zabbix agent
    • Key: mysql.status.alive
    • Type of information: Numeric (unsigned)
    • Data type: Decimal
    • Update interval: 30s
    • Applications: MySQL
  2. Create Trigger: Go to Configuration > Hosts, select your MySQL host, then Triggers > Create trigger.
    • Name: MySQL service is down on {HOST.NAME}
    • Severity: High
    • Expression: {<Host Name>:mysql.status.alive.last()}=0
  3. Create Graph: Optional, to visualize the uptime/downtime.

2. Monitoring Apache HTTP Server Performance

This involves enabling Apache's mod_status, creating an agent script to parse its output, and configuring a Zabbix UserParameter.

Step 1: Enable Apache Server Status

On the client machine running Apache, modify httpd.conf to enable mod_status and allow access from localhost:

# Edit Apache configuration file (e.g., /etc/httpd/conf/httpd.conf)
# Or in a site-specific configuration file.
<Location /server-status>
    SetHandler server-status
    Require local # Apache 2.4+
    # For Apache 2.2 and older, use:
    # Order deny,allow
    # Deny from all
    # Allow from 127.0.0.1
</Location>
ExtendedStatus On

If you have URL rewrite rules (e.g., in a .htaccess file for a PHP application like ThinkPHP), ensure the /server-status path is excluded from rewriting. Add this rule *before* any catch-all rewrite rules:

# Example for .htaccess
<IfModule mod_rewrite.c>
   RewriteEngine on
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_URI} !/server-status [NC] # Exclude /server-status
   RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]
</IfModule>

Restart Apache to apply changes:

sudo systemctl reload httpd # For systemd-based systems
# Or for SysVinit:
sudo /etc/init.d/httpd configtest # Verify syntax
sudo /etc/init.d/httpd graceful

Test access: curl http://127.0.0.1/server-status?auto. You should see raw Apache status output.

Step 2: Create Zabbix Agent Script for Apache

Create a directory for Zabbix custom scripts and place the Apache monitoring script there:

# On the Apache server (where agent is installed):
sudo mkdir -p /etc/zabbix/scripts
sudo vim /etc/zabbix/scripts/apache_monitor.sh

Content for apache_monitor.sh:

#!/bin/bash
# Zabbix Apache Monitor Script
# Version: 1.0
# Author: Rewritten by AI

# Configuration
APACHE_STATUS_URL="http://localhost/server-status?auto"
CACHE_FILE_PATH="/tmp/zabbix_apache_status.cache"
CACHE_LIFETIME_SECONDS=30 # Cache data for 30 seconds

# Function to fetch Apache status
fetch_apache_status() {
    local fetch_cmd=$(which curl || which wget)
    if [ -z "$fetch_cmd" ]; then
        echo "ZBX_NOTSUPPORTED: Missing curl or wget"
        exit 1
    fi

    # Determine the best fetch command options
    if [[ "$fetch_cmd" == *"curl"* ]]; then
        $fetch_cmd --insecure --silent --location "$APACHE_STATUS_URL" > "$CACHE_FILE_PATH"
    elif [[ "$fetch_cmd" == *"wget"* ]]; then
        $fetch_cmd --no-check-certificate --quiet -O - "$APACHE_STATUS_URL" > "$CACHE_FILE_PATH"
    fi
    return $?
}

# Check if cache is fresh, otherwise update
if [ ! -f "$CACHE_FILE_PATH" ] || \
   [ "$(find "$CACHE_FILE_PATH" -mmin +$((CACHE_LIFETIME_SECONDS / 60)) -print -quit)" ]; then
    fetch_apache_status
    if [ $? -ne 0 ]; then
        echo "ZBX_NOTSUPPORTED: Failed to fetch Apache status"
        exit 1
    fi
fi

# Ensure cache file exists and is not empty
if [ ! -s "$CACHE_FILE_PATH" ]; then
    echo "ZBX_NOTSUPPORTED: Apache status cache is empty or missing"
    exit 1
fi

# Parse the requested metric
case "$1" in
    "ping")
        grep -q 'Total Accesses' "$CACHE_FILE_PATH" &> /dev/null && echo 1 || echo 0
        ;;
    "TotalAccesses")
        awk '/^Total Accesses:/ {print $3}' "$CACHE_FILE_PATH"
        ;;
    "TotalKBytes")
        awk '/^Total kBytes:/ {print $3}' "$CACHE_FILE_PATH"
        ;;
    "CPULoad")
        awk '/^CPULoad:/ {print $2}' "$CACHE_FILE_PATH"
        ;;
    "Uptime")
        awk '/^Uptime:/ {print $2}' "$CACHE_FILE_PATH"
        ;;
    "ReqPerSec")
        awk '/^ReqPerSec:/ {print $2}' "$CACHE_FILE_PATH"
        ;;
    "BytesPerSec")
        awk '/^BytesPerSec:/ {print $2}' "$CACHE_FILE_PATH"
        ;;
    "BytesPerReq")
        awk '/^BytesPerReq:/ {print $2}' "$CACHE_FILE_PATH"
        ;;
    "BusyWorkers")
        awk '/^BusyWorkers:/ {print $2}' "$CACHE_FILE_PATH"
        ;;
    "IdleWorkers")
        awk '/^IdleWorkers:/ {print $2}' "$CACHE_FILE_PATH"
        ;;
    # Scoreboard parsing - counting characters
    "WaitingForConnection")
        awk '/^Scoreboard:/ {print gsub(/_/, "", $2)}' "$CACHE_FILE_PATH"
        ;;
    "StartingUp")
        awk '/^Scoreboard:/ {print gsub(/S/, "", $2)}' "$CACHE_FILE_PATH"
        ;;
    "ReadingRequest")
        awk '/^Scoreboard:/ {print gsub(/R/, "", $2)}' "$CACHE_FILE_PATH"
        ;;
    "SendingReply")
        awk '/^Scoreboard:/ {print gsub(/W/, "", $2)}' "$CACHE_FILE_PATH"
        ;;
    "KeepAlive")
        awk '/^Scoreboard:/ {print gsub(/K/, "", $2)}' "$CACHE_FILE_PATH"
        ;;
    "DNSLookup")
        awk '/^Scoreboard:/ {print gsub(/D/, "", $2)}' "$CACHE_FILE_PATH"
        ;;
    "ClosingConnection")
        awk '/^Scoreboard:/ {print gsub(/C/, "", $2)}' "$CACHE_FILE_PATH"
        ;;
    "Logging")
        awk '/^Scoreboard:/ {print gsub(/L/, "", $2)}' "$CACHE_FILE_PATH"
        ;;
    "GracefullyFinishing")
        awk '/^Scoreboard:/ {print gsub(/G/, "", $2)}' "$CACHE_FILE_PATH"
        ;;
    "IdleCleanupOfWorker")
        awk '/^Scoreboard:/ {print gsub(/I/, "", $2)}' "$CACHE_FILE_PATH"
        ;;
    "OpenSlotWithNoCurrentProcess")
        awk '/^Scoreboard:/ {print gsub(/\./, "", $2)}' "$CACHE_FILE_PATH"
        ;;
    *)
        echo "ZBX_NOTSUPPORTED: Unknown metric "$1""
        exit 1
        ;;
esac

exit 0

Grant execute permissions to the script:

sudo chmod +x /etc/zabbix/scripts/apache_monitor.sh

Ensure the Zabbix agent user can write to the cache file path, or change the CACHE_FILE_PATH to a Zabbix-owned directory like /var/lib/zabbix/tmp:

sudo chown zabbix:zabbix /tmp/zabbix_apache_status.cache # Or the chosen cache directory

Step 3: Configure Zabbix UserParameter

Create a custom UserParameter configuration file for Apache in /etc/zabbix/zabbix_agentd.d/:

sudo vim /etc/zabbix/zabbix_agentd.d/userparameter_apache.conf

Add the following line:

UserParameter=apache.status[*],/bin/bash /etc/zabbix/scripts/apache_monitor.sh $1

Restart the Zabbix agent:

sudo systemctl restart zabbix-agent # For systemd-based systems
# Or for SysVinit:
sudo /etc/init.d/zabbix-agent restart

Test the UserParameter from the Apache server:

sudo /etc/zabbix/scripts/apache_monitor.sh CPULoad
# Expected output: a numeric value for CPU load

Step 4: Create Zabbix Template/Items in Web GUI

In the Zabbix web interface:

  1. Create a Template: Go to Configuration > Templates > Create template (e.g., "Template App Apache HTTP").

  2. Create Items: For the "Template App Apache HTTP" template, navigate to Items > Create item for each metric you want to collect.

    • Name: Apache Total Accesses
    • Type: Zabbix agent
    • Key: apache.status[TotalAccesses]
    • Type of information: Numeric (unsigned)
    • Update interval: 60s
    • Applications: Apache

    Repeat for TotalKBytes, CPULoad, BusyWorkers, IdleWorkers, etc.

  3. Create Triggers: Set up triggers for critical conditions (e.g., Apache not reachable via apache.status[ping]).

  4. Link to Host: Go to Configuration > Hosts, select your Apache host, and link the "Template App Apache HTTP" template to it.

Configuring Alerting Mechanisms

Zabbix's strength lies in its flexible alerting. Here's how to set up basic email alerts:

1. Mail Server Setup (e.g., Postfix)

Ensure your Zabbix server can send emails. Install and configure a local Mail Transfer Agent (MTA) like Postfix.

# Install Postfix
yum install -y postfix mailx

# Start and enable Postfix
systemctl start postfix
systemctl enable postfix

# Configure mailx for sending emails via an external SMTP server (e.g., 163.com)
vim /etc/mail.rc
# Add these lines at the end:
# set from=your_email@163.com smtp=smtp.163.com
# set smtp-auth-user=your_username smtp-auth-password=your_app_password smtp-auth=login

Test email sending from the command line:

echo "This is a test email from Zabbix server." | mail -s "Zabbix Test" your_recipient_email@example.com

2. Create Zabbix Alert Script

Zabbix can execute custom scripts for alerts. Create a simple script to send emails:

# Zabbix alert scripts are typically located in /usr/lib/zabbix/alertscripts/
sudo vim /usr/lib/zabbix/alertscripts/send_email_alert.sh

Content for send_email_alert.sh:

#!/bin/bash
# Zabbix Email Alert Script
# Arguments: recipient_email, subject, message

RECIPIENT="$1"
SUBJECT="$2"
MESSAGE="$3"

if [ -z "$RECIPIENT" ] || [ -z "$SUBJECT" ] || [ -z "$MESSAGE" ]; then
    echo "Usage: $0 <recipient_email> <subject> <message>"
    exit 1
fi

echo "$MESSAGE" | /bin/mail -s "$SUBJECT" "$RECIPIENT"

Make the script executable:

sudo chmod +x /usr/lib/zabbix/alertscripts/send_email_alert.sh
sudo chown zabbix:zabbix /usr/lib/zabbix/alertscripts/send_email_alert.sh

3. Configure Zabbix Media Type

In the Zabbix web GUI:

  1. Navigate to Administration > Media types.
  2. Click "Create media type" or modify an existing "Email" type.
    • Name: Custom Email Alert
    • Type: Script
    • Script name: send_email_alert.sh (the script created above)
    • Script parameters: {ALERT.SENDTO}, {ALERT.SUBJECT}, {ALERT.MESSAGE}
    • Enable it.

4. Create Zabbix User and Associate Media

  1. Navigate to Administration > Users and create or select a user.
  2. Go to the "Media" tab for that user and click "Add".
    • Select the "Custom Email Alert" media type.
    • Enter the "Send to" address (e.g., your email).
    • Configure when the media should be active (e.g., 24/7) and which trigger severities it should receive.

5. Configure Zabbix Action

Actions define what happens when a trigger changes state (e.g., problem or recovery).

  1. Navigate to Configuration > Actions > Trigger actions and click "Create action".
  2. Action Tab:
    • Name: Send email on high severity problems
    • Default subject: Problem: {EVENT.NAME} on {HOST.NAME}
    • Default message: Trigger: {TRIGGER.NAME}\nHost: {HOST.NAME}\nStatus: {TRIGGER.STATUS}\nSeverity: {TRIGGER.SEVERITY}\nOriginal value: {ITEM.VALUE}\nURL: {TRIGGER.URL}
    • Conditions: Define which triggers (e.g., by severity, host group) should activate this action.
  3. Operations Tab:
    • Click "New" under "Operations".
    • Operation type: Send message
    • Send to Users: Select the user configured in Step 4.
    • Send only to: Custom Email Alert (the media type)

Now, when a configured trigger fires, Zabbix will execute your custom email script, sending an alert to the specified recipient.

Tags: Zabbix monitoring SNMP MariaDB apache

Posted on Fri, 15 May 2026 19:27:38 +0000 by Marc