生產環境常用 HAProxy 負載均衡 MySQL,需實時感知後端實例存活狀態。本文展示如何利用 Linux 守護進程 xinetd (extended Internet daemon) 快速將一個 Shell 檢查腳本暴露為 HTTP 服務:HAProxy → xinetd 端口 → Shell 腳本 → 返回 HTTP 狀態碼與信息,無需編寫任何網絡代碼。
HAProxy (TCP/HTTP 健檢)
│
▼
xinetd 監聽 9200 端口 (tcp)
│
├─ 收到連接
├─ fork 執行 /root/mysql_check.sh
├─ 捕獲腳本 stdout
└─ 直接作為 HTTP 響應返回
/root/mysql_check.sh#!/bin/bash
# 返回 HTTP 響應:狀態行 + 頭部 + 體
# 正常:HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nMySQL OK
# 異常:HTTP/1.1 503 Service Unavailable\r\nContent-Type: text/plain\r\n\r\nMySQL DOWN
if mysqladmin ping --silent; then
echo -e "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nMySQL OK"
exit 0
else
echo -e "HTTP/1.1 503 Service Unavailable\r\nContent-Type: text/plain\r\n\r\nMySQL DOWN"
exit 1
fi
chmod +x /root/mysql_check.sh
/etc/xinetd.d/mysql_checkservice mysql_check
{
disable = no
port = 9200
socket_type = stream
protocol = tcp
wait = no
user = root
server = /root/mysql_check.sh
# server_args = # 腳本無需參數時留空
log_on_failure += USERID
}
wait = no:並發處理每個連接(fork 模式)server:指定可執行腳本路徑echo "mysql_check 9200/tcp" >> /etc/services
systemctl restart xinetd # CentOS 7+/RHEL 7+
# 或
service xinetd restart # CentOS 6
# nc 測試
nc localhost 9200
# 輸出:
# HTTP/1.1 200 OK
# Content-Type: text/plain
# MySQL OK
# telnet 測試
telnet localhost 9200
backend mysql_cluster
option httpchk GET / HTTP/1.1\r\nHost:\ localhost
http-check expect status 200
server mysql1 10.0.0.1:3306 check port 9200 inter 2000 rise 2 fall 3
server mysql2 10.0.0.2:3306 check port 9200 inter 2000 rise 2 fall 3
HAProxy 定期向 9200 端口發送 HTTP 請求,根據返回狀態碼判斷 MySQL 實例健康狀態。
| 優點 | 缺點 |
|---|---|
| 零依賴,系統自帶 xinetd | 每請求 fork 進程,高併發下開銷大 |
| 腳本語言無關(bash/python/perl) | 無法處理 HTTPS/TLS |
| 部署極簡,適合健檢等低頻場景 | 響應頭需腳本手動構造,易出錯 |
timeout 2 mysqladmin ...)防止卡死阻塞 xinetd。only_from 限制來源 IP,增強安全性。xinetd + Shell 腳本是**將任意命令行工具快速 HTTP 化**的經典技巧,極適合 HAProxy/MySQL/Redis 等中間件的健康檢查端點構建。理解「inetd 模式:連接即執行、輸出即響應」的核心模型,能靈活解決許多「不想寫服務端代碼」的場景。